2016-04-03 76 views
1

我試圖將一個大的分割列表傳遞給函數'FreqDist'來查找最頻繁的單詞。如何通過nltk.FreqDist一個大的分割列表或文件

我分裂使用鹹菜如下列表:

import nltk 
import cPickle as pickle 
import sys 
import os 
import itertools as it 
for no,i in enumerate(it.islice(it.count(), 3, 33+3, 3)): 
    if no == 0: 
     fil = tokens[0:i] 
    else: 
     fil = tokens[i-3+1:i+1] 

    file_name = "/tmp/words/text" + str(no+1) + '.p' 
    files = open(file_name, "wb") 
    pickle.dump(fil, files) 
    files.close() 

現在我想用一類操作如下傳遞文件:

class Passer(object): 
    def __init__(self,path): 
     self.path = path 

    def __iter__(self): 
     return self 

    def __next__(self): 
     for fname in os.listdir(self.path): 
      with open(self.path + "/" + fname, "rb") as f: 
       fil = pickle.load(f) 
       yield fil 

passer = Passer(path="/tmp/words") 
words = nltk.FreqDist(passer) 

不幸的是,這樣做我得到這個錯誤:

TypeError: iter() returned non-iterator of type 'Passer' 

有沒有人有任何想法如何解決這個問題?

+2

Python 2中的迭代器必須定義'next'方法(不帶下劃線)。 – vaultah

+0

這就是說,我所做的將在python 3上工作,對吧? – alexmulo

+0

'__next__'可以在Python 3上運行,是的。不過,Python 3中沒有cPickle。 – vaultah

回答

0

嘗試:

FreqDist(chain(*[word_tokenize(line) for line in open('in.txt')])) 

如:

[email protected]:~$ echo """This is a foo bar sentence 
> Not any more hahaha""" > in.txt 
[email protected]:~$ cat in.txt 
This is a foo bar sentence 
Not any more hahaha 
[email protected]:~$ python 
Python 2.7.11 (default, Dec 15 2015, 16:46:19) 
[GCC 4.8.4] on linux2 
fType "help", "copyright", "credits" or "license" for more information. 
>>> from nltk import FreqDist 
>>> from itertools import chain 
>>> from nltk import word_tokenize 
>>> FreqDist(chain(*[word_tokenize(line) for line in open('in.txt')])) 
FreqDist({'a': 1, 'bar': 1, 'sentence': 1, 'This': 1, 'is': 1, 'hahaha': 1, 'Not': 1, 'foo': 1, 'any': 1, 'more': 1}) 
+0

這只是一種解決方法。也許你應該解釋如何擺脫'TypeError'呢? – vaultah

+0

嗨阿爾瓦斯非常感謝你的回答。它幫助我做這個生成器:'nltk.FreqDist(it.chain([pickle.load中的word for word(open(file_name)) for file_name in os.listdir(「/ tmp/words /」)])) 」。它工作得很好!有沒有可能使用類和__iter__函數做類似的事情?再次感謝 – alexmulo

+0

我認爲創建自己的課程來閱讀一個語料庫可能是一種矯枉過正的行爲。看一看已經在NLTK中編碼的語料庫閱讀器。這些可能會幫助你,https://github.com/nltk/nltk/tree/develop/nltk/corpus/reader – alvas

0

我存儲在以下文字到11泡菜文件:

text = 'The European Union’s plan to send refugees fleeing Syria’s civil war back to Turkey en masse could be illegal, a top UN official has said, as concerns mounted that Greece,Greece2' 

目錄稱爲字(路徑=/tmp目錄/單詞),並有11個名爲testo1,testo2等的文件。現在我找到了正確的理解,以達到自己的目標:

nltk.FreqDist([word for f in os.listdir("/tmp/words/") for word in pickle.load(open("/tmp/words/"+f))]) 

現在,似乎一切正常,但我問自己,如果這一步喂FreqDist一步或者如果是先加載列表比處理它。因爲我的想法是一步一步地加載和處理文件,而不是全部加載以節省內存。

再次感謝您的幫助。

相關問題