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