Home > Software design >  Counting occurrences of a word in a text file without count function
Counting occurrences of a word in a text file without count function

Time:02-24

I am learning Python and I'm supposed to create a program that takes user-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.


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

CodePudding user response:

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

CodePudding user response:

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)
  • Related