|
|
import re
def creation_of_dictionary(message):
print(f"In creation_of_dictionary: message= {message}")
m = {}
l = []
z4 = {}
mc = ['r', 'o', 't', 'e']
for i in message:
if i.isalpha():
b = i.lower()
l.append(b)
print(f"creation_of_dictionary:l={l}")
for g in range(len(l)):
f = l.count(l[g])
m[l[g]] = f
tuples = m.items()
tuples = sorted(tuples, key=lambda tuples: tuples[1])
print(f"tuples = {tuples}")
for e in [-4, -3, -2, -1]:
z4[mc[m]] = tuples[e][0]
z4[tuples[e][0]] = mc[e]
print(z4)
return (z4)
def decode(message, dict):
lists = []
for m in message:
l = m.lower()
lists.append(l)
for s in range(len(lists)):
if lists[s] in dict.keys():
lists[s] = dict[lists[s]]
b = ''.join(lists)
return b
def txt_decode(path):
lines = []
newdic = {}
m = open(path, 'r')
q = m.readlines()
m.close()
for i in range(len(q)):
q[i] = q[i].rstrip()
newdic = creation_of_dictionary(''.join(q))
for t in range(len(q)):
lines.append(decode(q[t], newdic))
f = open(path, 'a')
f2 = open("result.txt", 'w')
f.write("\n The encryption for the above text is:\n")
for n in range(len(lines)):
f.write(lines[n])
f2.write(lines[n])
f.write('\n')
f2.write('\n')
f.close()
def long_word(message_file):
register = re.compile('[^a-zA-Z]')
with open(message_file, 'r') as infile:
messages = infile.read().split()
max_option = len(max(messages, key=len))
word = [word for word in messages if len(word) == max_option]
final_word = []
for z in range(0, len(word)):
word[z] = register.sub('', word[z])
if len(word[z]) == max_option:
final_word.append(word[z])
return final_word
def file_length(f_mean):
with open(f_mean) as f:
for o, p in enumerate(f):
pass
return o + 1
def main():
txt_decode("message.txt")
f = open("message.txt", 'a')
long = long_word("result.txt")
num_of_try = file_length("result.txt")
for m in range(0, num_of_try):
f.write(long[0] + "")
f.write("\n")
f.close()
if __name__ == '__main__':
main()
Part 1
replace 4 most common letters in the text with 4 most common letters in the English language ‘e’,’t’,’o’,’r’.
in example: 'a' is most common - replace it with 'e', and 'e' with 'a'
in example: abcd most common chars in text: a <-> e, b <-> t, c <-> o, d <-> r
Create a function replace_common_occurences(str) -> replaced_dict - that will include the most common letters and their replacements.
The function needs to find the most common chars (count occurences)
The function will receive a text as a string and will return the relevant dictionary - replaced_dict
{'a': 'e', 'c': 'o', 'b': 't', 'e': 'a', 'd': 'r', 'o': 'c', 'r': 'd', 't': 'b'}
1. The dictionary will include only letters that were changed.
2. include only letters - not numbers, spaces, etc.
3. code must be case insensitive - dictionary only lower case
4. check:
a. There are at least four different letters in your text
b. for for every popular letter - there is no letter that appears the same number of times.
c. the most popular letters are not 'e', 't', 'o', 'r'
"""
"""
Part 2
1. Write a function replace_chars_in_text(text to change, replaced_dict) -> changed str
2. The function will iterate over the str and for each char
if there is a replaced_dict[key] - replace with the value, otherwise do not change.
3. Example: str = ///bha Taa3add, bha Tdaer, enr b7ha Fdcccccbbb
replaced_dict = {'a': 'e', 'c': 'o', 'b': 't', 'e': 'a', 'd': 'r', 'o': 'c', 'r': 'd', 't': 'b'}
replaced_str = ///the bee3err, the bread, and t7he frooooottt
"""
"""
Part 3
Create a function: decode_text(path to encrypted text file) to update the message text file
call:
1. replace_common_occurences(str) -> replaced_dict
2. replace_chars_in_text(text to change, replaced_dict) -> changed str
add to message.txt file: 'the encryption for the above text is:' ....decrypted text....
create another text file - results.txt - include only the decrypted results.
notes: common chars should be done over all text file, not line by line.
ignore \n.
"""
"""
Part 4
Create a function find_longest_word(path to results.txt) -> list of longest words.
return the longest word in result.txt file (decrypted text) - count only alphabetical chars.
Removing all non alpha chars - import re, regex=re.compile("[^a-zA-Z]") list[i]=regex.sub(", your string)
Create a function count_num_of_lines(path to results.txt) -> num of lines.
main()
1. decrypt message - part 1,2,3
2. write to the original message (append) the first value of the longest words list return from find_longest_word(path to results.txt)
times the number of lines in results.txt file.
Example: Your longest word is "BOOBOBA", The number of lines is 2.
Add to original message.txt - BOOBOBA BOOBOBA
"""
'Puackich, hvhnkrally oaths phufhck. All ymr nhhd is Pykemn.'
J.U.U.U Kmltin.
mmps iks nmk eio; ---> hkmu
"""
hi guys pls advise i added the code i managed to write and the H.W description below basically the code supposed to receive and than decode string message but i am getting errors such as message.txt file doesnt exist etc
|
|
|
|
|
אנטון מוטרוק 2021 wrote: errors such as message.txt file doesnt exist etc If you get errors then you need to provide the exact text, and explain which line they occurred on. Remember we have never seen this code before, have no idea what is is supposed to do or what data it is processing.
Also, instead of trying to write the entire application in one go, stop and look at the task(s) you have been set. Go by the numbers in your questions: write the code just for that step, and test it until it works successfully. Only then should you move on to the next step, and so on, until you complete the entire application.
|
|
|
|
|
As a new Python user, I got such an error as
'module' object has no attribute 'askopenfilename' in the piece of code below:
def getfile(title, filetype, ext):
root = tkinter.Tk()
root.withdraw()
# open window on top of other windows
root.attributes("-topmost", True)
filename = filedialog.askopenfilename(initialdir=r"C:\Users\...\Testing\AHCS Map Update\2022_Test",
title= title,
filetypes=(("{}".format(filetype),
"*.{}".format(ext)),
("all files","*.*")))
return filename
Referring to Python Examples of tkinter.filedialog.askopenfilename[^] the
attribute 'askopenfilename' is used. How can this
'askopenfilename' be properly called? Thanks.
|
|
|
|
|
|
Using Python 2.7 and run in VS2019, my Python script has errors. Mycode is below
import os
import arcpy
import numpy as np
import pandas as pd
import tkinter
from tkinter import filedialog
import time
import zipfile
...
def getfile(title, filetype, ext):
root = tkinter.Tk() root.withdraw()
...
A red wave-line is below the
root.withdraw() , and the error message is
Unexpected token 'root' .
In my CPU, the
Anaconda3 is installed
C:\Users\...\Anaconda3\Lib\site-packages\jedi\third_party\typeshed\stdlib\3\tkinter . In my Environmental Variables, there is such an item as
C:\Users\...\Anaconda3
How to debug it? Thanks if you can help.
|
|
|
|
|
That is not valid Python, it should be:
def getfile(title, filetype, ext):
root = tkinter.Tk()
root.withdraw()
|
|
|
|
|
What do you mean? Could you hint me clearly? Thanks.
|
|
|
|
|
It could not be any clearer, what do you not understand?
|
|
|
|
|
Seriously?
You cannot have two statements on the same line!
|
|
|
|
|
|
def ListOfLists(list):
'''
This function receives a list, which can contain elements that are themselves lists and
returns those items separately in a single list.
If the parameter is not of type list, it must return null.
Receive an argument:
list: The list that can contain other lists and is converted to a
list of unique or non-iterable elements.
Ex:
ListOfLists([1,2,['a','b'],[10]]) should return [1,2,'a','b',10]
ListOfLists(108) should return null.
ListOfLists([[1,2,[3]],[4]]) should return [1,2,3,4]
|
|
|
|
|
|
We're curious. A virtual environment can use system wide resources, but can a virtual environment lean on an existing venv and only have the extra bits, or overide bits, that are specific to that new venv?
cheers
Chris Maunder
|
|
|
|
|
I'm curious: Is any VM implementation programmed in Python? (Recursive virtualization or not!)
|
|
|
|
|
The virtual environment just puts itself (i.e its version of Python and associated libraries) at the front of the search path. So anything called after you run activate , will load first from the .venv locations, before looking at the system folders. I guess that if you then activate another .venv then the search path would be venv2 -> venv1 -> system installation . Which could be fun.
|
|
|
|
|
I guess I could do this manually, since it's only really the site-packages I'm worried about. Something like
Suppose I have two apps that have different and potentially conflicting packages. I'd create a venv with the python interpreter in /app/bin/python and the common packages in /app/bin/python/site-packages-common. I'd then install specific packages for app A and B in different folders:
/app/bin/python
/app/bin/python/site-packages-common
/app/bin/python/site-packages-A
/app/bin/python/site-packages-B
then in app A I could do
sys.path.insert(0, "/app/bin/python/site-packages-common")
sys.path.insert(0, "/app/bin/python/site-packages-A")
and in app B I could do
sys.path.insert(0, "/app/bin/python/site-packages-common")
sys.path.insert(0, "/app/bin/python/site-packages-B")
I would have to specify the target folder when running pip to install the packages (no drama).
My big concern is if we have the following:
pip install common-package -target /app/bin/python/site-packages-common
pip install package-a -target /app/bin/python/site-packages-A
pip install package-b -target /app/bin/python/site-packages-B
What if package-a relies on v1 of common-package, and package-b relies on v2 of common-package?
I'm actually assuming pip will install all dependent packages anyway, so while we might end up with repeated installs of dependant packages, there are certainly some 'common' packages that won't necessarily be dependencies of anything and so will only be installed once in the common folder
cheers
Chris Maunder
|
|
|
|
|
I've never come across a situation which would need A and B to co-exist in that way, so it's difficult to give a useful answer. But unless you are running A and B at (more or less) the same time in the same shell, do you really need to share between them?
|
|
|
|
|