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

When counting the occurrence of a string in a file, my code does not count the very first word

代码

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()

问题

基本上我正在尝试读取文件并计算文件中每个单词出现的次数,然后打印该单词及其旁边出现的次数。

除了不计算文件中的第一个单词外,一切正常。

我正在使用的文件

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

This file is for testing. It is going to test how many times the words in here appear.

输出

('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)

注意

如果您注意到它说 'This' 出现了 0 次,但它确实出现在文件中。

有什么想法吗?

我猜是这一行:

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

您正在查找 "space" + YourWord + "space",并且第一个单词前面没有 space。

您检查 line 是否包含 ' '+item+' ',这意味着您正在搜索从 开始 并以 space 结尾的词。因为“This”是该行的第一个字,所以它没有被两个space包围。

要解决此问题,您可以使用以下代码:

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

以上代码确保正确计算第一个和最后一个单词。

问题出在这一行wordcount=line.count(' '+item+' ')。第一个单词前面不会有 space。我还从您的代码中删除了一些其他冗余语句:

import string

def main():
    try:
        #file=input('Enter the name of the file you wish to open: ')
        thefile=open('C:/Projects/Python/data.txt','r')
        line=thefile.readline()
        line = line.translate(string.maketrans("",""), string.punctuation)
        thefilelist=line.split()
        d={}
        for item in thefilelist:
            if item not in d:
                d[item] = 0
            d[item] = d[item]+1 
        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()

This前面没有space' '

快速修复:

line= ' ' + thefile.readline()

但是你的代码中有很多问题。 例如:

  • 多行文件呢?
  • 文件末尾没有 . 怎么办?

如果你想要一个简单的修复,这一行很简单:

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

"This"前没有space。

我认为有几种方法可以修复它,但我建议使用 with 块并使用 .readlines()

我建议使用更多的 python 功能。在这种情况下,有几个建议。如果文件不止一行,则此代码将不起作用。另外,如果一个句子是 words... lastwordofsentence.Firstwordofnextsentence,它就不会起作用,因为它们将彼此相邻并成为一个词。请将您的替换更改为 spaces,我的意思是将 '' 更改为 ' ',因为拆分将替换多个 spaces。

此外,请 post 无论您使用的是 Python 2.7 还是 3.X。它有助于解决可能出现的小语法问题。

filename = input('Enter the name of the file you wish to open: ')
# Using a with block like this is cleaner and nicer than try catch
with open(filename, "r") as f:
    all_lines = f.readlines()

d={} # Create empty dictionary

# Iterate through all lines in file
for line in all_lines:

    # Replace periods and commas with spaces
    line=line.replace('.',' ')
    line=line.replace(',',' ')

    # Get all words on this line
    words_in_this_line = line.split() # Split into all words

    # Iterate through all words
    for word in words_in_this_line:
        #Check if word already exists in dictionary
        if word in d: # Word exists increment count
            d[word] += 1
        else: #Word doesn't exist, add it with count 1
            d[word] = 1

# Print all words with frequency of occurrence in file
for i in d.items():
    print(i)  

我建议更多地使用 Python 实用程序。一个很大的缺陷是你只从文件中读取一行。

然后你创建一组独特的单词,然后开始单独计算它们,这是非常低效的;该行被遍历多次:一次创建集合,然后遍历每个唯一的单词。

Python 有一个内置的 "high performance counter" (https://docs.python.org/2/library/collections.html#collections.Counter),专门用于这样的用例。

以下几行替换你的程序;它还使用 "re.split()" 按单词边界 (https://docs.python.org/2/library/re.html#regular-expression-syntax) 拆分每一行。

想法是在文件的每一行上执行此 split() 函数,并使用此拆分的结果更新 wordcounter。另外 re.sub() 用于在将行交给 split 函数之前一次性替换点和逗号。

import re, collections

with open(raw_input('Enter the name of the file you wish to open: '), 'r') as file:
    for d in reduce(lambda acc, line: acc.update(re.split("\W", line)) or acc,
                     map(lambda line: re.sub("(\.,)", "", line), file),
                     collections.Counter()).items():
        print d