uaveiro-leci/1ano/1semestre/fp/aula07/countLetters.py

34 lines
884 B
Python
Raw Normal View History

2022-11-09 14:52:30 +00:00
import sys
def main():
2022-11-21 18:05:44 +00:00
letters = countLetters(sys.argv[1])
2022-11-09 14:52:30 +00:00
# Print the results
for c in sorted(letters.keys()):
print(c, letters[c])
2022-11-21 18:05:44 +00:00
# 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
2022-11-21 18:05:44 +00:00
# Returns the dictionary with the letters
return letters
2022-11-09 14:52:30 +00:00
if __name__ == "__main__":
main()