如何在for循环中迭代项目,然后将for循环迭代结果打印到文本文件中?

时间:2018-10-24 15:06:59

标签: python for-loop

我想将for循环的输出存储到文本文件中,但不是所需的输出,因为它们每次只会打印最后一个元素。 请看一下第二个for循环(我试图将for循环的输出放在文本文件中,但是它们似乎总是将最后一个元素保存到文本文件中)...

f(q)

arr的输出是:

import

4 个答案:

答案 0 :(得分:1)

上下文处理程序在离开作用域后将自动关闭其资源。 open()有一个上下文处理程序,可以这样使用:

with open('text_file1.txt', 'w') as f_out:
    for item in arr:
        f_out.write("%s\n" % str(item))

在您的代码中,调用text_file.close(),它将仅在写入第一个条目后关闭文件处理程序。在第一条write()声明之后,您如何不会出错?

答案 1 :(得分:0)

只需在单个操作中写入整个数组,因此在写入每个元素之后,您不会覆盖文件。您可以在{SilverSlash注释中使用with open()方法,也可以使用numpy.savetxt方法处理整数或浮点数列表。

import numpy    
numpy.savetxt('arr.out', arr, delimiter=',')

修改

在第二个循环中,删除处理书写部分的行,并在脚本末尾添加numpy.savetxt('arr.out', arr, delimiter=',')。请记住要import numpy添加脚本的开头。

for item in arr:
    # get the top scoring item
    top_item = sorted_t.pop(0)
    # create dictionary and keep key as topic id and filename
    # and probability in tuple as value
    dic_topic_doc.setdefault(top_item[0], []).append((filenames[index], top_item[1])
numpy.savetxt('arr.out', arr, delimiter=',')

编辑2

看起来像列表arr是包含嵌套列表的元组列表。因此numpy.savetxt不起作用。而是使用

for item in arr:
        # get the top scoring item
        top_item = sorted_t.pop(0)
        # create dictionary and keep key as topic id and filename
        # and probability in tuple as value
        dic_topic_doc.setdefault(top_item[0], []).append((filenames[index], top_item[1])

with open('arr.txt', 'w') as f:
    for item in arr:
        f.write("%s\n" % str(item))

答案 2 :(得分:0)

如果您想保留当前代码而不导入额外的库:

print('\nTopic id, number of documents, list of documents with probability and represented topic words: ')
dic_topic_doc = {}
# for doc in doc_clean:
for index, doc in enumerate(doc_clean):
    bow = dictionary.doc2bow(doc)
    # get topic distribution of the ldamodel
    t = ldamodel.get_document_topics(bow)
    # sort the probability value in descending order to extract the top
    # contributing topic id
    sorted_t = sorted(t, key=lambda x: x[1], reverse=True)
    # print only the filename
    arr = []
    r = filenames[index], sorted_t
    arr += [r]
# print(filenames[index], sorted_t)
text_file = open("text_file1.txt", "a") # Just changing the open mode from w(rite) to a(ppend) does the trick
for item in arr:
    text_file.write("%s\n" % str(item))
    text_file.close()
    # get the top scoring item
    top_item = sorted_t.pop(0)
    # create dictionary and keep key as topic id and filename
    # and probability in tuple as value
    dic_topic_doc.setdefault(top_item[0], []).append((filenames[index], top_item[1]))

我还建议您阅读Python documentation的相关部分。

答案 3 :(得分:0)

from collections import defaultdict as ddict

dic_topic_doc = ddict(list)

text_file = open("text_file1.txt", "w")
with open('text_file1.txt', 'a') as f:
    for item in arr:
        f.write(f"{item}\n")
        top_item = sorted_t.pop(0)
        dic_topic_doc.append((filenames[index], top_item[1]))

尝试一下。