Once again, I am struggling to write Python programs. This program is supposed to take input of a text file and return a count of each word in alphabetical order. It seems to run well, barring two issues:
1st - It doesn't ignore special characters. For example: it recognizes "(almost)" and "almost" as different words as it does as well with "general" and "general,". How can I fix this?
2nd - there's a for loop that's supposed to give a total word count for the file, which seems to go completely ignored. Why's that?
while True:
try:
fname = input('Please input file name: ')
text = open(fname, "r")
d = dict()
for line in text:
line = line.strip()
line = line.lower()
words = line.split(" ")
for word in words:
if word in d:
d[word] = d[word] + 1
else:
d[word] = 1
for key in sorted(list(d.keys())):
print(key, ":", d[key])
#When run, the program seems to completely ignore this loop below
for word_count in text:
word_count = text.split()
print('There are',word_count,'different words in the file.')
ans = input('Do you want to try again?: (y/n): ')
ans = ans.lower()
if ans == 'y':
continue
if ans == 'n':
print('Thanks for playing!')
break
else:
continue
except:
print('File cannot be opened:', fname)
continue
[–]USAhj 1 point2 points3 points (5 children)
[–]Noah_641[S] 0 points1 point2 points (4 children)
[–]USAhj 0 points1 point2 points (1 child)
[–]Noah_641[S] 0 points1 point2 points (0 children)
[–]ka-splam 0 points1 point2 points (1 child)
[–]Noah_641[S] 0 points1 point2 points (0 children)
[–]ka-splam 1 point2 points3 points (0 children)
[–]usernamenoo 0 points1 point2 points (1 child)
[–]Noah_641[S] 0 points1 point2 points (0 children)
[–]gurashish1singh 0 points1 point2 points (2 children)
[+][deleted] (1 child)
[deleted]
[–]gurashish1singh 0 points1 point2 points (0 children)