# Community Practice Problem-2 (File handling)

Write a Python program to count the frequency of words in a file.

sample content of file :
" What is Python language?
Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in
languages such as C++ or Java.
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles.It features a dynamic type system and automatic memory management and has a large and comprehensive standard library. The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with Python. "

Sample output : Number of words in the file : Counter({‘this’: 7, ‘Append’: 5, ‘text.’: 5, ‘text.Append’: 2, ‘Welcome’: 1, 'to
': 1, ‘w3resource.com.’: 1})

1 Like

file=open(“test.txt”,‘x’)
import os
frequency = {}
document = open(‘test.txt’, ‘r’)
text_string = document.read().lower()
match_pattern = re.findall(r’\b[a-z]{3,15}\b’, text_string)
for word in match_pattern:
count = frequency.get(word,0)
frequency[word] = count + 1

frequency_list = frequency.keys()
for words in frequency_list:
print(words, frequency[words])