2010-10-10 75 views
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 
+0

在模塊'profile'中運行一個profiler,看看有什麼說的。 – John 2010-10-10 20:38:45

回答

8

如果你只是想字數的頻率,那麼你就需要創建nltk.Text對象,甚至使用nltk.PlainTextReader。相反,直接去nltk.FreqDist。或者,如果您不想進行任何分析 - 只需使用dict即可。如果您不想做任何分析 - 只需使用dict即可。如果您不想進行任何分析,請使用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 

這些可以取得多大用生成器表達式更有效,但我已經習慣爲可讀性循環。