I have built a tiny script count the word frequencies of all text files with a specified directory. I would be glad to receive any suggestions and feedback.
import re, glob,os
from collections import OrderedDict, Counter
class CountWords:
def __init__(self,dir,ext):
self.dir = dir
self.ext = ext
@property
def files(self):
#collect all the files with `.txt` extension
os.chdir(self.dir)
return glob.glob(f"**/*.{self.ext}", recursive=True)
@property
def contents(self):
#concatenate files
cat_content = []
for file in self.files:
with open(file, 'r') as f:
content = f.read()
cat_content.append(content)
contents = ",".join(cat_content)
return contents
@property
def words(self):
words = re.findall(r"[a-zA-z_]+", self.contents)
words = [word.lower() for word in words]
return words
def count(self):
words_counter = Counter(self.words)
words_counter = OrderedDict(sorted(words_counter.items(),key=lambda t:t[1], reverse=True))
return words_counter
The function version:
def count_words(dir,ext):
os.chdir(dir)
#collect all the files with `.txt` extension
files = glob.glob(f"**/*.ext", recursive=True)
#concatenate files
cat_content = []
for file in files:
with open(file, 'r') as f:
content = f.read()
cat_content.append(content)
contents = ",".join(cat_content)
#extract the words
words = re.findall(r"[a-zA-z_]+", contents)
words = [word.lower() for word in words]
words_counter = Counter(words)
words_counter = OrderedDict(sorted(words_counter.items(),key=lambda t:t[1], reverse=True))
return words_counter