I need to read the letter from a .txt file and print the number of occurrence in txt file. so far i have been able to print the content in one line but having issue with the cou
Here you go. Hopefully your professor will ask you to explain your work.
grades = open('grades.txt').read().split()
for grade in sorted(set(grades),
key=lambda x: ord(x[0])*3-('+'in x)+('-'in x)):
print ('{} students got {}'.format(grades.count(grade), grade))
You can use collections.Counter for this
with open('grades.txt') as f:
print(Counter(f.read()))
Example
this is a test that has letters
Output
Counter({'t': 7,
' ': 6,
's': 5,
'a': 3,
'h': 3,
'e': 3,
'i': 2,
'l': 1,
'r': 1})
Or to only include letters
from string import ascii_letters
with open('grades.txt') as f:
print(Counter(i for i in f.read() if i in ascii_letters))
Edit
Without the use of any other libraries, the manual way to do the same thing as above:
from string import ascii_letters
d = {}
with open('grades.txt') as f:
for letter in d.read():
if letter in ascii_letters:
if letter in d:
d[letter] += 1
else:
d[letter] = 1
If your file looks something like
A A+ B B- B B+ B+ A A- B+
Then the modification to the above code would be
d = {}
with open('grades.txt') as f:
for grade in d.read().split():
if grade in d:
d[grade] += 1
else:
d[grade] = 1