Python practice every day (1): Calculate the most frequently used words in each article in a folder,
# Coding: utf-8import OS, repath = 'test' files = OS. listdir (path) def count_word (words): dic ={} max = 0 marked_key = ''# calculate the number of times each word appears for word in words: if dic. has_key (word) is False: dic [word] = 1 else: dic [word] = dic [word] + 1 # Compare the values of each dictionary, obtain the largest number for key, value in dic. items (): if dic [key]> max: max = dic [key] marked_key = key # print the number of times words and words appear in the for loop (marked_key, max) for f in files: with open (OS. path. join (path, f) as diary: words = re. findall ("[a-zA-Z] + '*-* [a-zA-z]", diary. read () count_word (words)
# Has_key (key): The function is used to determine whether the key exists in the dictionary. If the key is returned in the dictionary dict, true is returned. Otherwise, false is returned. It is used to determine whether keys in the dictionary have appeared.
This is a daily small project of Python on Git. I will not submit it over there and write it here.
Project address: https://github.com/Yixiaohan/show-me-the-code