how to turn a text(single string) into a dictionary with frequencies of words in text

Viewed 43

I'm trying to turn a single text string into a dictionary with the frequencies of the words as values. Afterward, I want to feed the dictionary into wordcloud. I removed cases punctuations and unwanted frequent small words. This is what I did.

def calculate_frequencies(file_contents):
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", \
"we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its", "they", "them", \
"their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be", "been", "being", \
"have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when", "where", "how", \
"all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very", "can", "will", "just"]

result = {}
list_contents = file_contents.lower().split()
for word in list_contents:
    if word.isalpha():
        if word not in result:
            result[word] = 0
        result[word] += 1
    for punctuation in punctuations:
        if word.endswith(punctuation):
            word = word[:word.index(punctuation)]
            if word not in result:
                result[word] = 0
            result[word] += 1
    if word.endswith("'s"):
        word = word[:-2]
        if word not in result:
            result[word] = 0
        result[word] += 1
for words in uninteresting_words:
    if words in result:
        del result[words]
return result

Unfortunately it didn't work and I don't know what's the problem since I'm new to programming.

0 Answers
Related