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

Python 2.7 计算一个单词在文本文件中出现的次数,python-2.7,Python 2.7,你试过什么?有什么例外?代码至少会遇到两个与计算字符串中的单词无关的异常。for i in text将逐个返回每个字符,因此所有其他条件相同时,您只能通过这种方式找到单个字符的单词。接下来,假设这个问题已经解决,s=i.index(…)将返回找到该单词的字符串中的位置,因此按s递增将使您的计数产生很大的偏差。另外,如果找不到该单词。这实际上对您有利,因为您并不真正关心索引,您只想知道它是否被找到? def paraula(file,wordtofind): f = open(file,


你试过什么?有什么例外?代码至少会遇到两个与计算字符串中的单词无关的异常。
for i in text
将逐个返回每个字符,因此所有其他条件相同时,您只能通过这种方式找到单个字符的单词。接下来,假设这个问题已经解决,
s=i.index(…)
将返回找到该单词的字符串中的位置,因此按
s
递增将使您的计数产生很大的偏差。另外,如果找不到该单词。这实际上对您有利,因为您并不真正关心索引,您只想知道它是否被找到?
def paraula(file,wordtofind):

    f = open(file,"r")
    text = f.read()
    f.close()
    count = 0
    for i in text:
        s = i.index(wordtofind)
        count = count + s
    return count
paraula (file,wordtofind)
def paraula(file,wordtofind):
    f = open(file,"r")
    text = f.read()
    f.close()
    count = 0
    index = text.find(wordtofind) # Returns the index of the first instance of the word
    while index != -1:
        count += 1
        text = text[index+len(wordtofind):] # Cut text starting from after that word
        index = text.find(wordtofind) # Search again
    return count

paraula (file,wordtofind)
def word_count(filename, word):
    with open(filename, 'r') as f:
        return f.read().count(word)