Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading