2017-02-01 57 views
0

我是一个新用户到Python,我试图环以下几点:如何循环,打印和保存输出在一个数组

text = open('filename.txt', 'rU').read() 
splitter = Splitter() 
postagger = POSTagger() 
splitted_sentences = splitter.split(text) 
pos_tagged_sentences = postagger.pos_tag(splitted_sentences) 
dicttagger = DictionaryTagger([ 'dicts/positive.yml', 'dicts/negative.yml']) 
dict_tagged_sentences = dicttagger.tag(pos_tagged_sentences) 
scoreposneg = sentiment_score(dict_tagged_sentences) 
dicttagger = DictionaryTagger([ 'dicts/positive.yml', 'dicts/negative.yml', 'dicts/inc.yml', 'dicts/dec.yml', 'dicts/inv.yml']) 
dict_tagged_sentences = dicttagger.tag(pos_tagged_sentences) 
scoretotal = sentiment_total(dict_tagged_sentences) 
print scoretotal 

在此之前,我已经建立了类分配器,POSTagger, DictionaryTagger,sentiment_total,还创建了5个不同的字典。这对我在Python上运行1个文件(我从打印scoretotal得到一个数字)是有效的。但是,当我试图创建一个循环并打印所有输出(我的目录中有650个文件)时,它不起作用(没有打印任何内容)并且scoretext.txt文件中有0.0个文件。

path = '/mydirectory' 
files = glob.glob(path) 
for file in files: 
    text = open(file, 'rU').read() 
    splitter = Splitter() 
    postagger = POSTagger() 
    splitted_sentences = splitter.split(text) 
    pos_tagged_sentences = postagger.pos_tag(splitted_sentences) 
    dicttagger = DictionaryTagger([ 'dicts/positive.yml', 'dicts/negative.yml']) 
    dict_tagged_sentences = dicttagger.tag(pos_tagged_sentences) 
    scoreposneg = sentiment_score(dict_tagged_sentences) 
    dicttagger = DictionaryTagger([ 'dicts/positive.yml', 'dicts/negative.yml', 'dicts/inc.yml', 'dicts/dec.yml', 'dicts/inv.yml']) 
    dict_tagged_sentences = dicttagger.tag(pos_tagged_sentences) 
    scoretotal = sentiment_total(dict_tagged_sentences) 
    print scoretotal 

scoretotal = np.zeros((1,650)) 
scoretotal_no = 0 
scoretotal_no = scoretotal_no + 1 

np.savetxt("scoretext.txt", scoretotal, delimiter=" ", fmt="%s") 

如果有人能够提供一些见解,真的很感激。谢谢!

+0

我不知道我明白这是应该做的('scoretotal'是外循环复位?),但你怎么从'打印获得(文件)''之前在文件中的文件:'?另外,'file'是Python 2.x中的内置函数,所以我会选择其他名称。 – roganjosh

+0

嗨Roganjosh,我得到了[]。我已将文件更改为文件名。我以为我将650分保存到一个数组中,所以它必须在循环之外 –

+0

好吧,所以首先循环本身不起作用,因为'path ='/ mydirectory''给你一个空列表' files = glob.glob(path)'(没有什么可以迭代)。这隔离了一个问题。但是'scoretotal = np.zeros((1,650))'完全破坏了'scoretotal'循环过程中可能积累的任何数据。实际上,每个循环都会破坏前一次迭代的数据(我假设,但我不知道'sentiment_total()'的作用)。 – roganjosh

回答

0

您的问题可能是您如何访问目录中的文件。看到这一点: Use a Glob() to find files recursively in Python?

+0

嗨,尼克,我也试过了(但它也没有工作): directory = os.path.join(“/ textanalysisfiles”,“path”) for root, dirs,os.walk中的文件(目录): 文件中的文件: –

+0

同意@roganjosh,文件是python中的保留名称,所以使用其他内容,甚至:file_list中的文件 –