0

My aim: To count the frequency of a user entered word in a text file.(in python) I tried this.But it gives the frequency of all the words in the file.How can i modify it to give the frequency of a word entered by the user?

from collections import Counter
word=input("Enter a word:")
def word_count(test6):
        with open('test6.txt') as f:
                return Counter(f.read().split())

print("Number of input words in the file :",word_count(word))

This may be a naive question but I am just beginning to code.So please try to answer. Thanks in advance.

3
  • Well first you will need to use input() to allow the user to give you the word they are interested in. then you can look for that word in your Counter Commented Mar 29, 2020 at 16:33
  • I used input() to give the input.But still, it's displaying the count of all words. Commented Mar 29, 2020 at 16:42
  • Please update your code to show that. but you will also just want to print the word from the counter not all the counts Commented Mar 29, 2020 at 16:43

2 Answers 2

1

to find the frequency of a word in a file you can just join all the lines from your file using str.join and then just use str.count:

def word_count(word):
    with open('test6.txt') as f:
            return ''.join(f).count(word)


print("Number of words in the file :", word_count(input('give me a word')))

also you may use for word count in the text:

def word_count(word):
        with open('test6.txt') as f:
                return f.read().count(word)
Sign up to request clarification or add additional context in comments.

Comments

1

While str.count works nice if you only look up one word, the approach with Counter is better when you want to get multiple word-counts and have a bigger text to search through (say a whole book, some megabyte of data).

In that case you can read your book once into a Counter and query it multiple times. You need to clean up data though, f.e. newlines and punctation have to be removed so you find 'so' inside 'Is that so?':

import string
from collections import Counter
# fixed text, normally you read your file here
text = """This text has punctation
as well as newlines. No -word- will
be unaccounted for. This text should do
as test text for now. no no no"""

# make a translation to remove punctuation and newlines from the text
# before splitting it into words that you then count once
punct = string.punctuation
p = str.maketrans(punct + "\n\r", ' '*(len(punct)+2))

wc = Counter(text.translate(p).split())

# repeatedly ask your counter how often the word occured
while True:
    word=input("Enter a word: ") 
    if not word.strip():
        break 
    print(f"'{word}' occures {wc.get(word,0)} times.") 

Output:

Enter a word: text
'text' occures 3 times.
Enter a word: has
'has' occures 1 times.
Enter a word: do
'do' occures 1 times.
Enter a word: no
'no' occures 3 times.
Enter a word: 

If you can do regex, you could also extract words by regex, more here: Extracting words from a string, removing punctuation and returning a list with separated words

1 Comment

@kederra now it will. And counter has a use if you have a bigger text and want to get multiple word counts from it without rereading the text from the file over and over again. for a one time count your solution is fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.