NLTK PlaintextCorpusの単語をより速く数えるにはどうすればよいですか?
質問
ドキュメントのセットがあり、各タプルに特定のドキュメントの日付があり、そのドキュメントに特定の検索用語が表示される回数があるタプルのリストを返したいと思います。私のコード(以下)は機能しますが、遅いです。私はN00Bです。これをより速くするための明らかな方法はありますか?より良いコーディングを学ぶことができるだけでなく、このプロジェクトをより速く実行できるように、どんな助けも大歓迎です!
def searchText(searchword):
counts = []
corpus_root = 'some_dir'
wordlists = PlaintextCorpusReader(corpus_root, '.*')
for id in wordlists.fileids():
date = id[4:12]
month = date[-4:-2]
day = date[-2:]
year = date[:4]
raw = wordlists.raw(id)
tokens = nltk.word_tokenize(raw)
text = nltk.Text(tokens)
count = text.count(searchword)
counts.append((month, day, year, count))
return counts
解決
単語数の頻度が必要な場合は、作成する必要はありません nltk.Text
オブジェクト、または使用します nltk.PlainTextReader
. 。代わりに、すぐに行きます nltk.FreqDist
.
files = list_of_files
fd = nltk.FreqDist()
for file in files:
with open(file) as f:
for sent in nltk.sent_tokenize(f.lower()):
for word in nltk.word_tokenize(sent):
fd.inc(word)
または、分析をしたくない場合は、 dict
.
files = list_of_files
fd = {}
for file in files:
with open(file) as f:
for sent in nltk.sent_tokenize(f.lower()):
for word in nltk.word_tokenize(sent):
try:
fd[word] = fd[word]+1
except KeyError:
fd[word] = 1
これらは発電機の表現ではるかに効率的にすることができますが、読みやすいループに使用されます。
所属していません StackOverflow