将包含字符串文字的python嵌套列表保存到由制表符分隔的文件中

时间:2018-06-18 10:15:53

标签: python list save nested-lists string-literals

我想存储一个像这样的python嵌套列表:

document_list = [['This', 'is', 'the', 'title', '\n\n\n\n', 'Rest', 'of', 
  'the', 'first', 'document'], ['Second', 'Document', '\t', 'title', '\n\n\n\n']]

如何保存列表,将每个单词作为原始字符串? 我试过这样的话:

with open('doc_list.txt', 'w', encoding="utf-8") as file:
    file.writelines('\t'.join(doc) + '\n' for doc in document_list)

但是,它自然不会将字符串文字写为原始字符串。 有人知道如何解决这个问题吗?谢谢!

更新:我期望的输出文本文件应如下所示:

This   is   the   title   \n\n\n\n   Rest   of   the   first   document
Second   Document   \t   title   \n\n\n\n

总有一个标签空间顺便说两句......

2 个答案:

答案 0 :(得分:0)

这将创建2个文件并将其存储到document0.txt和document1.txt

document_list = [['This', 'is', 'the', 'title', '\n\n\n\n', 'Rest', 'of',
                  'the', 'first', 'document'], ['Second', 'Document', '\t', 'title', '\n\n\n\n']]

doc = [' '.join(i) for i in document_list]
for i in range(0, len(doc)):
    with open('document' + str(i) + '.txt', 'w') as f:
      f.write(doc[i])

答案 1 :(得分:0)

只写为JSON?

<div *ngIf="isDisplayed; else showItem2">Item 1</div>

<ng-template #showItem2>
Item 2
</ng-template>