【问题标题】:Counting the number of occurrences of a word in a text file计算一个单词在文本文件中出现的次数
【发布时间】:2017-08-14 00:32:04
【问题描述】:

我想计算在文本文件中找到每个单词的次数,但不知道哪里出了问题。当我运行它时,我得到的计数为 0。我也很难找到一种方法来将单词大写的出现包括在计数中(同时计算 dog 和 Dog 的出现)

def main():
text_file = open("textfile.txt", "r")

dog_count = 0
cat_count = 0

for word in text_file.readlines():
    if word == 'dog':
        dog_count= dog_count + 1
    else:
        dog_count= dog_count

print('the word dog occurs',dog_count,'times')

【问题讨论】:

标签: python word-count


【解决方案1】:

我相信您的问题是您正在循环文件的行而不是单词。您需要添加另一个循环来遍历每个单词。

警告:下面的示例未经测试,但应该足够接近。

def main():
    text_file = open("textfile.txt", "r")

    dog_count = 0
    cat_count = 0

    for line in text_file.readlines():
        for word in line.split():
            if word == 'dog':
                dog_count= dog_count + 1

    print('the word dog occurs',dog_count,'times')

【讨论】:

【解决方案2】:

您可以在搜索过程中将文本设置为大写/小写:

定义主(): text_file = open("textfile.txt", "r")

dog_count = 0
cat_count = 0

for line in text_file.readlines():
    for word in line.split():
        word = word.lower() #case convertion
        if word == 'dog':
            dog_count= dog_count + 1

print "The word dog occurs",dog_count,"times"

main()

它应该可以正常工作,经过测试并且对我来说可以正常工作。 :)

【讨论】:

    【解决方案3】:

    答案:关于“为什么输出错误”的问题 - 您需要遍历行中的每个单词。

    建议: 当您搜索多个单词时,您可以将它们放在一个字典中并将计数存储为相应字典键的值。

    文件内容:

    Hi this is hello
    Hello is my name
    

    然后

    text_file.read()
    

    会给,

    ['Hi this is hello\n', 'Hello is my name\n']
    
    text_file.read().splitlines()
    ['Hi this is hello', 'Hello is my name']
    

    然后拆分行中的每一行,

    lines = map(str.split,text_file.read().splitlines())
    [['Hi', 'this', 'is', 'hello'], ['Hello', 'is', 'my', 'name']]
    

    在链接可迭代对象时,

    it.chain.from_iterable(map(str.split,text_file.read().splitlines()))
    ['Hi', 'this', 'is', 'hello', 'Hello', 'is', 'my', 'name']
    

    还有,

    search=['dog','cat'] # the words that you need count
    search = dict.fromkeys(search,0) # will give a dict as {'dog':0,'cat':0}
    

    因此对于您的问题,

    def main():
            text_file =  open("textfile.txt", "r")
            search=['cat','dog']
            search = dict.fromkeys(search,0)
            import itertools as it
            res=dict()
            for word in it.chain.from_iterable(map(str.split,text_file.read().splitlines())):
                    if word.lower() in search:
                            search[word.lower()]=search[word.lower()]+1
            for word,count in search.iteritems():
                    print('the word %s occurs %d times'%(word,count))
    

    这也可以计算区分大小写的单词!

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多