Thomas Hutton
Thomas Hutton

Reputation: 77

Counting occurrences of a word in a text file without count function

I am learning Python, and I'm supposed to create a program that takes a user's input for a single word and then returns the number of times that word occurs in the text file. I really don't know what I'm doing wrong or how to go about this, been wracking for hours watching videos and such. I can't use the `.count() function.

Here is my code:

import string
frank = open('Frankenstein.txt','r',encoding='utf-8')
frank_poem = frank.read()

frank_poem = frank_poem.translate(str.maketrans('','',string.punctuation))

split_poem = frank_poem.split()

word = input("Please enter the word you would like to count in Frankenstein (case-sensitive): ")

def word_count(word):
    total = 0
    for word in split_poem:
        total += word
    return total

print(word_count(word))

Upvotes: 1

Views: 1197

Answers (3)

Obaskly
Obaskly

Reputation: 724

import string
frank = open('Frankenstein.txt','r',encoding='utf-8')
frank_poem = frank.read()

frank_poem = frank_poem.translate(str.maketrans('','',string.punctuation))

split_poem = frank_poem.split()

word = input("Please enter the word you would like to count: ")

def word_count():
    total = 0
    for wordi in split_poem:
        if wordi == word:
            total += 1
    return total

print(word_count())

Upvotes: 0

constantstranger
constantstranger

Reputation: 9379

Here is a working solution:

def word_count(word):
    total = 0
    for poem_word in split_poem:
        if word == poem_word:
                total += 1
    return total

print(word_count(word))

Here is an alternative that is more concise but does not use count. It relies on the fact that a boolean value of True (such as when poem_word == word is True) gets converted to an integer value of 1 for the built-in function sum().

def word_count(word):
    return sum(poem_word == word for poem_word in split_poem)

Upvotes: 0

BrokenBenchmark
BrokenBenchmark

Reputation: 19252

total += word

is adding a string, word, to total. You probably are looking for total += 1, rather than total += word. You'll then need to add an if statement to check if the word you're currently examining is equivalent to the target word, like so:

def word_count(target_word):
    total = 0
    for word in split_poem:
        if word == target_word:
            total += 1
    return total

Upvotes: 1

Related Questions