计算文件中字符串的出现次数时,我的代码不计算第一个单词

iWa*_*his 4 python string text file readline

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()
Run Code Online (Sandbox Code Playgroud)

问题

基本上我试图读取文件并计算文件中每个单词出现的次数,然后打印该单词与它旁边出现的次数.

这一切都有效,除了它不会计算文件中的第一个单词.

我正在使用的文件

我正在测试此代码的练习文件包含以下文本:

此文件用于测试.它将测试这里出现的单词的次数.

产量

('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)
Run Code Online (Sandbox Code Playgroud)

注意

如果你注意到它说'This'出现了0次,但它实际上出现在文件中.

有任何想法吗?

Gui*_*rme 7

我的猜测就是这一行:

wordcount=line.count(' '+item+' ')

您正在寻找"空间"+ YourWord +"空格",并且第一个单词前面没有空格.