-
Hey everone, so I had this exercise : “Write a program that reads a file and prints the letters And I managed to solve it, and here’s a part of my code :
And it works just fine. However, I was looking up for other solutions online and I found one in the answer section of the book(Python for everybody), it’s pretty much like mine but it has an extra line :
I was wondering why the following line is added ? Because the code just works fine without it
|
Beta Was this translation helpful? Give feedback.
Replies: 8 comments
-
Without being able to absolutely confirm this, I believe this is a historical oddity. The behavior of strings changed between Python 2 and Python 3; the tuple() line is likely necessary for Python 2 support with Unicode? |
Beta Was this translation helpful? Give feedback.
-
I dont think there is a real reason. I think the only one reason that i have in mind is maybe to split the tasks of words and twords. The output of letters with twords and words are the same (I didnt tried it but I’m sure of that). To test the output of words and twords you can do something like this:
and if the output is True than the output are the same (I’m sure it will). Hope to solve your doubts -Gabriele- |
Beta Was this translation helpful? Give feedback.
-
Thanks! I’m not sure but maybe it’s what you’re saying because in some of the book slides,there are references to Python 2. |
Beta Was this translation helpful? Give feedback.
-
Yeah I think it’s used maybe to explain a little more about what’s going on. And yes the output is exactly the same Thanks ! |
Beta Was this translation helpful? Give feedback.
-
Dont forget to set it as solution 🙂 |
Beta Was this translation helpful? Give feedback.
-
Where did you count the frequency of alphabets? |
Beta Was this translation helpful? Give feedback.
-
Well here is no count. But it’s easy to add.
|
Beta Was this translation helpful? Give feedback.
-
Oh, everything turns out to be so simple, but I solved it using the methods of the py4e books + a little help on github, because I could not fully understand the assignment import string
fileName = input('Enter a file name: ')
file = open(fileName)
count = 0
d = dict()
lst = list()
for line in file:
line = line.translate(line.maketrans('', '', string.digits))
line = line.translate(line.maketrans('', '', string.punctuation))
line = line.lower()
words = line.split()
for word in words:
for letter in word:
count += 1
d[letter] = d.get(letter, 0) + 1
for k, v in list(d.items()):
lst.append((v / count, k))
lst.sort(reverse=True)
for k, v in lst:
print(f'{v} {k:.3f}') |
Beta Was this translation helpful? Give feedback.
I dont think there is a real reason. I think the only one reason that i have in mind is maybe to split the tasks of words and twords. The output of letters with twords and words are the same (I didnt tried it but I’m sure of that). To test the output of words and twords you can do something like this: