uaveiro-leci/1ano/fp/aula09/countLetters2.py

35 lines
966 B
Python
Raw Normal View History

2022-12-05 17:53:38 +00:00
import sys
def main():
letters = countLetters(sys.argv[1])
# Print the results
for c in sorted(letters, key=letters.get, reverse=True):
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.")
2023-01-30 16:48:43 +00:00
# This is the same function used in ../aula07/countLetters.py
2022-12-05 17:53:38 +00:00
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__":
main()