reddit praw api を使用して、reddit の投稿タイトルで最も人気のある単語を見つけるためのコードをいくつか書きました。
import nltk
import praw
picksub = raw_input('\nWhich subreddit do you want to analyze? r/')
many = input('\nHow many of the top words would you like to see? \n\t> ')
print 'Getting the top %d most common words from r/%s:' % (many,picksub)
r = praw.Reddit(user_agent='get the most common words from chosen subreddit')
submissions = r.get_subreddit(picksub).get_top_from_all(limit=200)
hey = []
for x in submissions:
hey.extend(str(x).split(' '))
fdist = nltk.FreqDist(hey) # creates a frequency distribution for words in 'hey'
top_words = fdist.keys()
common_words = ['its','am', 'ago','took', 'got', 'will', 'been', 'get', 'such','your','don\'t', 'if', 'why', 'do', 'does', 'or', 'any', 'but', 'they', 'all', 'now','than','into','can', 'i\'m','not','so','just', 'out','about','have','when', 'would' ,'where', 'what', 'who' 'I\'m','says' 'not', '', 'over', '_', '-','after', 'an','for', 'who', 'by', 'from', 'it', 'how', 'you', 'about' 'for', 'on', 'as', 'be', 'has', 'that', 'was', 'there', 'with','what', 'we', '::', 'to', 'the', 'of', ':', '...', 'a', 'at', 'is', 'my', 'in' , 'i', 'this', 'and', 'are', 'he', 'she', 'is', 'his', 'hers']
already = []
counter = 0
number = 1
print '-----------------------'
for word in top_words:
if word.lower() not in common_words and word.lower() not in already:
print str(number) + ". '" + word + "'"
counter +=1
number +=1
already.append(word.lower())
if counter == many:
break
print '-----------------------\n'
そのため、subreddit 'python' を入力して 10 件の投稿を取得すると、次のように返されます。
- 「パイソン」
- 「ピピ」
- 'コード'
- '使用する'
- '136'
- '181'
- 「だ...」
- 「アイパイソン」
- '133'
10.「158」
このスクリプトが数字や「d...」などのエラー ワードを返さないようにするにはどうすればよいですか? 最初の 4 つの結果は受け入れられますが、この残りを意味のある言葉に置き換えたいと思います。リストを common_words にするのは不合理であり、これらのエラーをフィルター処理しません。私はコードを書くことに比較的慣れていないので、助けていただければ幸いです。