python - 从以换行符分隔的不同列中的元组列表写入文本文件
问题描述
我有一个列表中的元组列表,该列表是句子列表,在元组中标记了相应的单词。
[[('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标签。我搜索了一下,但没有运气!请帮忙?:)
解决方案
用于\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")
是的,它有更多的行,另一方面它更容易调试和更改。
推荐阅读
- python - 在 for 循环中使用类方法
- javascript - 计算 Angular 数组的总数
- azure - 限制 Azure 功能上的服务器数量(消耗计划)
- java - Java AutoViewer JNLP 文件的网络连接错误
- nginx - Nginx 入口控制器与 HAProxy 负载均衡器
- zend-framework3 - RestAPI的ZF3开发:处理Post请求
- google-maps - 如何使用谷歌地图 API 的地理位置将当前位置设置为文字当前位置?
- java - JavaFX Table fx:factory show ImageView
- coldfusion - 使用 cfscript new StoredProc() 时如何获取存储过程的结果
- javascript - 复选框限制功能发生后复选框变得不可点击reactjs