Search This Blog
Exploring the Wonders of Science, Technology, and Human Potential
Featured
- Get link
- X
- Other Apps
Python Count Word Frequency
1.
def
count_occurrences(paragraph, word):
- This line defines a function called `count_occurrences` that takes two parameters: `paragraph` (the input paragraph) and `word` (the word or phrase to count).
2.
words = paragraph.split()
- This line splits the input `paragraph` into a list of words. It uses the `split()` method, which by default splits the string based on whitespace.
3.
count = words.count(word)
- This line uses the `count()` method to count how many times the `word` appears in the `words` list (which represents the words in the paragraph).
4.
return count
- This line returns the count of occurrences of the `word` in the `paragraph` back to the caller of the `count_occurrences` function.
5.
if __name__ == "__main__":
- This line checks if the script is being run as the main program.
6.
paragraph = input("Enter the paragraph: ")
- This line prompts the user to enter the paragraph and stores the input in the variable `paragraph`.
7.
word_to_count = input("Enter the word or phrase to count: ")
- This line prompts the user to enter the word or phrase they want to count in the paragraph and stores the input in the variable `word_to_count`.
8.
occurrences = count_occurrences(paragraph, word_to_count)
- This line calls the `count_occurrences` function with the `paragraph` and `word_to_count` as arguments, and stores the returned count in the variable `occurrences`.
9.
print(f"The word/phrase '{word_to_count}' appears {occurrences} times in the paragraph.")
- This line prints the result,
indicating how many times the specified word or phrase appears in the
paragraph.
def count_occurrences(paragraph, word):
- Get link
- X
- Other Apps
Popular Posts
What If India Loses this mindset of Reusing Things?
- Get link
- X
- Other Apps
Polar Bear is Suffering to Find Land Here is Why?
- Get link
- X
- Other Apps
Smarter move through technology revolution
- Get link
- X
- Other Apps
The Role of UX Design in Evolving Technology
- Get link
- X
- Other Apps
Comments
Post a Comment