python - 在尝试将列表写入 .txt 文件时,并非所有参数都在字符串格式化期间转换
问题描述
我想将列表写入 .txt 文件,这是我的列表:
[('Visible', 'JJ'),
('Landscape', 'NN'),
('Landscape', 'NN'),
('characteristics', 'NNS'),
('derived', 'VBN'),
('from', 'IN'),
('satellite-tracking', 'JJ'),
('data', 'NNS'),
('of', 'IN'),
('wintering', 'VBG'),
('habitats', 'NNS'),
('used', 'VBN'),
('by', 'IN'),
('oriental', 'JJ'),
('honey', 'NN'),
('buzzards', 'NNS'),
('in', 'IN'),
('Borneo', 'NNP')]
这是我编写该列表的代码:
with open('result.txt', 'w') as filehandle:
filehandle.writelines("%s\n" % item for item in list)
但不知何故,它显示了以下错误:
TypeError Traceback (most recent call last)
<ipython-input-47-8d6e1711d648> in <module>()
3
4 with open('cobahasil1.txt', 'w') as filehandle:
----> 5 filehandle.writelines("%s\n" % kata for kata in merged)
<ipython-input-47-8d6e1711d648> in <genexpr>(.0)
3
4 with open('cobahasil1.txt', 'w') as filehandle:
----> 5 filehandle.writelines("%s\n" % kata for kata in merged)
TypeError: not all arguments converted during string formatting
有人能帮我吗?谢谢
解决方案
迭代中的每个项目都是tuple
具有 2 个元素的。
所以你只需要提取所有元素:
tuples_list = [('Visible', 'JJ'),
('Landscape', 'NN'),
('Landscape', 'NN'),
('characteristics', 'NNS'),
('derived', 'VBN'),
('from', 'IN'),
('satellite-tracking', 'JJ'),
('data', 'NNS'),
('of', 'IN'),
('wintering', 'VBG'),
('habitats', 'NNS'),
('used', 'VBN'),
('by', 'IN'),
('oriental', 'JJ'),
('honey', 'NN'),
('buzzards', 'NNS'),
('in', 'IN'),
('Borneo', 'NNP')]
with open('result.txt', 'w') as filehandle:
filehandle.writelines("%s %s\n" % item for item in tuples_list)
推荐阅读
- python-3.x - 从 python 调用 CPLEX 时如何创建日志文件
- c# - FlowListView 列间距
- c++ - 无法构造具有给定数据类型的 Multimap
- playframework - Play Framework 将 val 放入 Action Builder Scala
- angular - 自定义指令中的抽象离开传单指令
- sql - 如果日期之间没有订单,Oracle SQL 返回 0 计数
- tensorflow - 什么 ImagePairData 层在 Caffe 中意味着什么?
- javascript - 读取从特定端口接收到的数据 C#
- c - 如何从每一行的文件中读取数据并将其存储到结构数组中
- sapui5 - 如何在 Fiori App 中更改 shell 标题