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

时间:2015-10-02 22:38:04

标签: python-2.7

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)

2 个答案:

答案 0 :(得分:3)

Why reinvent the wheel?

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

答案 1 :(得分:0)

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)