I have a python assignment that has to do with character occurrence. I have to extract all the characters (letters to be precise) in a poem and count how many of each letters there are.
For an example:
Bobby goes to school blahhhh blahhh blahhh
To:
B---6
o---5
y---1 ...etc
I have to write a code using a txt document and use the cat function to run my code and the poem. But i can only use dictionary to write this code. My code is below but it does not counts the number of each letters in the poem, it only counts the lines. I've been battling with it forever but no luck.
dict = {}
print "Frequency list:"
while True:
char = raw_input()
if char == 'END':
break
if char.isalpha():
if char in dict:
dict[char] = dict[char] + 1
else:
dict[char] = 1
for char, count in dict.items():
print char ,'\t', count
totalchars = 0
for char, count in dict.items():
totalchars += count
print totalchars, "characters total"
so I asked my teacher and he says that if I under stand the two codes below, I would be able to fix the problem in my code. I understand it but :/ ...still no luck.
dict = {}
while True:
word = raw_input()
if word == '-1':
break
if word in dict:
dict[word] = dict[word] + 1
else:
dict[word] = 1
for word, count in dict.items():
print word,'\t', count
print 'Number of unique words:', len(dict)
totalWords = 0
for word, count in dict.items():
totalWords += count
print 'Total number of words:', totalWords
myList = []
while True:
line = raw_input()
if line == '-1':
break
for char in line:
if char.isalpha():
myList.append(char)
myList.append('\n')
for char in myList:
print char,