如何在数组中循环,打印和保存输出

时间:2017-02-01 11:27:43

标签: python arrays loops numpy glob

我是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

在此之前,我已经为Splitter,POSTagger,DictionaryTagger,sentiment_total设置了类,还创建了5个不同的词典。当我在Python上运行1个filen时,这是有效的(我从print 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")

如果有人可以就此提供一些见解,我们将非常感激。谢谢!

1 个答案:

答案 0 :(得分:0)

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