collections.Counter()
может сделать это для вас. Я не смог добраться до вашей ссылки на данные, но скопировав и вставив текст, который вы опубликовали в качестве примера, вот как это можно сделать:
>>> import collections
>>> s = "in above approach I want to create most frequent and least frequent
words from list of sentences, but my attempt didn't produce that outuput?
what should I do? any elegant way to make this happen? any idea? can anyone
give me possible idea to make this happen? Thanks"
>>> c = dict(collections.Counter(s.split()))
>>> c
{'in': 1, 'above': 1, 'approach': 1, 'I': 2, 'want': 1, 'to': 3, 'create': 1,
'most': 1, 'frequent': 2, 'and': 1, 'least': 1, 'words': 1, 'from': 1,
'list': 1, 'of': 1, 'sentences,': 1, 'but': 1, 'my': 1, 'attempt': 1,
"didn't": 1, 'produce': 1, 'that': 1, 'outuput?': 1, 'what': 1, 'should': 1,
'do?': 1, 'any': 2, 'elegant': 1, 'way': 1, 'make': 2, 'this': 2, 'happen?':
2, 'idea?': 1, 'can': 1, 'anyone': 1, 'give': 1, 'me': 1, 'possible': 1,
'idea': 1, 'Thanks': 1}
>>> maxval = max(c.values())
>>> print([word for word in c if c[word] == maxval])
['to']
Сначала вы захотите удалить знаки препинания и т. П .; в противном случае, например, happen
и happen?
считаются двумя разными словами. Но вы заметите, что c
- это словарь, в котором ключи - это слова, а значения - сколько раз слово появляется в строке.
РЕДАКТИРОВАТЬ: Вот то, что будет работать через список нескольких твитов, как у вас. Вы можете использовать регулярное выражение, чтобы сначала упростить каждый твит до всех строчных букв, без знаков препинания и т. Д.
from collections import Counter
import re
fakenews = ["RT @GOPconvention: #Oregon votes today. That means 62 days until the @GOPconvention!",
"RT @DWStweets: The choice for 2016 is clear: We need another Democrat in the White House. #DemDebate #WeAreDemocrats ",
"Trump's calling for trillion dollar tax cuts for Wall Street.",
"From Chatham Town Council to Congress, @RepRobertHurt has made a strong mark on his community. Proud of our work together on behalf of VA!"]
big_dict = {}
for tweet in fakenews:
# Strip out any non-alphanumeric, non-whitespaces
pattern = re.compile('([^\s\w]|_)+')
tweet_simplified = pattern.sub('', tweet).lower()
# Get the word count for this Tweet, then add it to the main dictionary
word_count = dict(Counter(tweet_simplified.split()))
for word in word_count:
if word in big_dict:
big_dict[word] += word_count[word]
else:
big_dict[word] = word_count[word]
# Start with the most frequently used words, and count down.
maxval = max(big_dict.values())
print("Word frequency:")
for i in range(maxval,0,-1):
words = [w for w in big_dict if big_dict[w] == i]
print("%d - %s" % (i, ', '.join(words)))
Выход:
Word frequency:
3 - the, for
2 - rt, gopconvention, on, of
1 - oregon, votes, today, that, means, 62, days, until, dwstweets, choice, 2016, is, clear, we, need, another, democrat, in, white, house, demdebate, wearedemocrats, trumps, calling, trillion, dollar, tax, cuts, wall, street, from, chatham, town, council, to, congress, reproberthurt, has, made, a, strong, mark, his, community, proud, our, work, together, behalf, va