Python 计算一个单词在文本文件中出现的次数

Python 计算一个单词在文本文件中出现的次数,python,word-count,Python,Word Count,我想数一数在文本文件中找到每个单词的次数,但不确定是什么错了。当我运行它时,我得到的计数为0。我也很难找到一种方法来计算单词大写的出现次数(同时计算狗和狗的出现次数) 我相信你的问题在于你是在循环文件的行,而不是文字。您需要添加另一个循环来遍历每个单词 警告:以下示例未经测试,但应足够接近 def main(): text_file = open("textfile.txt", "r") dog_count = 0 cat_count = 0 for line

我想数一数在文本文件中找到每个单词的次数,但不确定是什么错了。当我运行它时,我得到的计数为0。我也很难找到一种方法来计算单词大写的出现次数(同时计算狗和狗的出现次数)


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

警告:以下示例未经测试,但应足够接近

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

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

def main(): text_file=open(“textfile.txt”、“r”)

main()


它应该运行良好,经过测试,对我来说运行良好。:)

回答:关于“为什么输出错误”的问题,您需要反复阅读行中的每个单词

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

文件内容:

Hi this is hello
Hello is my name
然后

会给,

['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']
以及

所以对于你的问题,

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))
这也得到了大小写敏感词的计数


希望有帮助

可能重复您在行上而不是单词上的迭代。您是正确的,它不会这样做。我想给你举一些去掉标点符号的例子。
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))