countLetters.py improvement
This commit is contained in:
parent
7233b8ee67
commit
5436272dbd
|
@ -2,25 +2,32 @@ import sys
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
# Read the file
|
letters = countLetters(sys.argv[1])
|
||||||
f = open(sys.argv[1], 'r')
|
|
||||||
text = f.read()
|
|
||||||
f.close()
|
|
||||||
|
|
||||||
# Count the letters
|
|
||||||
letters = {}
|
|
||||||
for c in text:
|
|
||||||
if c.isalpha():
|
|
||||||
c = c.lower()
|
|
||||||
if c in letters:
|
|
||||||
letters[c] += 1
|
|
||||||
else:
|
|
||||||
letters[c] = 1
|
|
||||||
|
|
||||||
# Print the results
|
# Print the results
|
||||||
for c in sorted(letters.keys()):
|
for c in sorted(letters.keys()):
|
||||||
print(c, letters[c])
|
print(c, letters[c])
|
||||||
|
|
||||||
|
# Print the most used letter and the number of times it's used
|
||||||
|
usedTheMostCount = max(letters.values())
|
||||||
|
usedTheMost = [letter for letter in letters.keys() if letters[letter] == usedTheMostCount][0]
|
||||||
|
print(f"A letra mais usada foi '{usedTheMost}', usada {usedTheMostCount} vezes.")
|
||||||
|
|
||||||
|
|
||||||
|
def countLetters(filename):
|
||||||
|
# Read the file and count the letters
|
||||||
|
letters = {}
|
||||||
|
with open(filename, 'r') as f:
|
||||||
|
for c in f.read():
|
||||||
|
if c.isalpha():
|
||||||
|
c = c.lower()
|
||||||
|
if c not in letters:
|
||||||
|
letters[c] = 0
|
||||||
|
letters[c] += 1
|
||||||
|
|
||||||
|
# Returns the dictionary with the letters
|
||||||
|
return letters
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue