code
def main():
try:
file=input('Enter the name of the file you wish to open: ')
thefile=open(file,'r')
line=thefile.readline()
line=line.replace('.','')
line=line.replace(',','')
thefilelist=line.split()
thefilelistset=set(thefilelist)
d={}
for item in thefilelist:
thefile.seek(0)
wordcount=line.count(' '+item+' ')
d[item]=wordcount
for i in d.items():
print(i)
thefile.close()
except IOError:
print('IOError: Sorry but i had an issue opening the file that you specified to READ from please try again but keep in mind to check your spelling of the file you want to open')
main()
Problem
Basically, I try to read the file and count the number of times each word in the file appears, and then print that word with the number of times that it appeared next to it.
Everything works, except that it will not read the first word in the file.
File i am using
my practice file in which I am testing this code contains this text:
This file is intended for testing. He will check how many times the words appear here.
Exit
('for', 1)
('going', 1)
('the', 1)
('testing', 1)
('is', 2)
('file', 1)
('test', 1)
('It', 1)
('This', 0)
('appear', 1)
('to', 1)
('times', 1)
('here', 1)
('how', 1)
('in', 1)
('words', 1)
('many', 1)
Note
If you notice that this means that 'This' appears 0 times, but it does appear in the file.
any ideas?