簡體   English   中英

將帶有字符串文字包括標記的python嵌套列表保存到由制表符分隔的文件中

[英]Save python nested list with string literals included tokens to file delimited by tab

我想存儲這樣的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個文件並將其存儲在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])

只是寫成JSON嗎?

import json

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.write(json.dumps(document_list))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM