user5367640
user5367640

Reputation:

Count how many times a word appears in a text file

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)

Upvotes: 2

Views: 1318

Answers (2)

CivFan
CivFan

Reputation: 15092

Why reinvent the wheel?

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

Upvotes: 3

mbinette
mbinette

Reputation: 5094

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)

Upvotes: 0

Related Questions