jeudi 21 novembre 2019

Randomly pick a value from each list in a dictionary in python

I have the following code:

result = set()
with open("words.txt") as fd:    
    for line in fd:
        matching_words = {word for word in line.lower().split() if len(word)==4 and "'" not in word}
        result.update(matching_words)      
print(result)
print(len(result))

result_dict = {}

for word in result:
    result_dict[word[2:]] = result_dict.get(word[2:], []) + [word]
print(result_dict)
print({key: len(value) for key, value in result_dict.items()})

Output

This takes a .txt file finds all the unique four letter words and excludes any that include an apostrophe. These words are then split using the last 2 characters. Each of the word endings are then added to a dictionary with the number of words containing that ending displayed as the value.

What I now need to do is disregard any list with less than 30 words in it. Then randomly select one word from each of the remaining lists and print the list of words.




Aucun commentaire:

Enregistrer un commentaire