Counting Frequency of Words in a Text File
In this article, we will focus on how to count the frequency of specific words in a text file. This process is often used in text analysis and natural language processing. We will use Python as our programming language for this example.
Sample Text File
Consider the following sample text file:
hypersonic, personal, personnel, personally, hypersonic, person, personnel, hypersonic, personal, person, personnel, personally, hypersonic, person, personnel, hypersonic, personal, person, personnel, hypersonic, person, personnel, hypersonic, personal, person, personnel, hypersonic, person, personnel, hypersonic, personal, person, personnel, hypersonic, person
In this example, we want to count the frequency of the words: "personal", "personnel", "personally", and "hypersonic".
Python Code
Here is the Python code to count the frequency of the words:
import re
from collections import Counter
# Sample text
text = "hypersonic, personal, personnel, personally, hypersonic, person, personnel, hypersonic, personal, person, personnel, personally, hypersonic, person, personnel, hypersonic, personal, person, personnel, hypersonic, person, personnel, hypersonic, personal, person, personnel, hypersonic, person, personnel, hypersonic, personal, person, personnel, hypersonic, person"
# Split text into words
words = re.findall(r'\w+', text.lower())
# Count word frequency
word_count = Counter(words)
# Print frequency of desired words
desired_words = ["personal", "personnel", "personally", "hypersonic"]
for word, count in word_count.items():
if word in desired_words:
print(f"{word}: {count}")
The output of the code is:
hypersonic: 12
personal: 6
personnel: 6
personally: 3
Counting the frequency of specific words in a text file is a simple process that can be done using Python. The Counter class from the collections module is particularly useful for this task. By using regular expressions to split the text into words, we can easily count the frequency of each word.