首页 > 解决方案 > 从以换行符分隔的不同列中的元组列表写入文本文件

问题描述

我有一个列表中的元组列表,该列表是句子列表,在元组中标记了相应的单词。

[[('This', 'DT'), ('is', 'VBZ'), ('the', 'DT'), ('house', 'NN')], 
[('This', 'DT'), ('is', 'VBZ'), ('the', 'DT'), ('car', 'NN')], 
[('This', 'DT'), ('is', 'VBZ'), ('the', 'DT'), ('dog', 'NN')]]

我想将它写入文本文件。预期输出:

This DT
is VBZ
the DT
house NN

This DT
is VBZ
the DT
car NN

This DT
is VBZ
the DT
dog NN

将其写入文件后

with open("new.txt","w") as wf:
     wf.write('\n'.join(' '.join(str(x) for x in tu) for tu in tag) )

我得到的文件是这样的,它不是预期的输出。

('This', 'DT') ('is', 'VBZ') ('the', 'DT') ('house', 'NN')
('This', 'DT') ('is', 'VBZ') ('the', 'DT') ('car', 'NN')

我怎样才能达到上面提到的结果:用'\n'(列(句子)之间的间隙)分隔的句子和相应第二列中单词的pos标签。我搜索了一下,但没有运气!请帮忙?:)

标签: pythonfile

解决方案


用于\n\n获取数组元素之间的空行。用于\n数组中的项目,空格 ( ) 用于元组:

with open("new.txt", "w") as wf:
    wf.write('\n\n'.join('\n'.join(' '.join(x) for x in tu) for tu in tag))

如果表达式变得太复杂,您总是可以回到更一步一步的方法:

with open("new.txt", "w") as wf:
    for block in tag:            # outer array
        for line in block:       # inner array
            for word in line:    # tuples
                wf.write(word)
                wf.write(" ")
            wf.write("\n")
        wf.write("\n")

是的,它有更多的行,另一方面它更容易调试和更改。


推荐阅读