4
我有一組文檔,我想返回一個元組列表,其中每個元組都有給定文檔的日期以及給定搜索詞在該文檔中出現的次數。我的代碼(如下)有效,但速度很慢,而且我是n00b。有沒有明顯的方法可以讓這個更快?任何幫助將非常感謝,主要是爲了讓我可以學習更好的編碼,但也使我可以更快地完成此項目!如何更快速地計算nltk plaintextcorpus中的單詞?
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
在模塊'profile'中運行一個profiler,看看有什麼說的。 – John 2010-10-10 20:38:45