python - 如何将列表列表的字符串转换为列表?
问题描述
我有这个文件,它是 MapReduce 作业的结果,因此它具有key-value
以下格式:
'null\t[0, [[0, 21], [1, 4], [2, 5]]]\n'
'null\t[1, [[0, 3], [1, 1], [2, 2]]]\n'
我想删除除此值列表的第二个元素之外的所有字符:
[[0, 21], [1, 4], [2, 5]]
[[0, 3], [1, 1], [2, 2]]
最后,将每个添加到一个列表中:
[[[0, 21], [1, 4], [2, 5]], [[0, 3], [1, 1], [2, 2]]]
这是我迄今为止的尝试:
with open(FILENAME) as f:
content = f.readlines()
for line in content:
# Just match all the chars upto "[[" then replace the matched chars with "["
clean_line = re.sub(r'^.*?\[\[', '[', line)
# And remove "\n" and the last 2 "]]" of the string
clean_line = re.sub('[\n]', '', clean_line)[:-2]
corpus.append(clean_line)
输出:
['[0, 21], [1, 4], [2, 5]', '[0, 3], [1, 1], [2, 2]']
你可以看到它仍然是str
打字,我怎样才能让它list
打字?
解决方案
将其视为一行 json 并根据需要将部分行替换为 json 文档
import json
corpus = [json.loads(line.replace('null\t', '{"a":').replace("\n", "}"))["a"][1] for line in content]
推荐阅读
- sql-server-2008 - 条件数据类型转换 | SQL 服务器
- xcode - 由于 Firebase 升级后缺少框架 GoogleToolboxForMac 而导致崩溃
- r - 如何存储循环表数据
- c# - CSVHelper 7.1.1 - 未找到与索引 0 处的 ['sp_ac_input_voltage_unit'] 名称匹配的标头
- c# - 使用相同的 SMTP (C#) 发送电子邮件和传真时出错
- postgresql - 使用 Apache NiFi 加载 postgres 表时出现 UUID 数据类型问题
- python - Python Splinter:如何截取整页截图?
- regex - 正则表达式匹配字符串的子字符串
- javascript - 无法将 JSON 转换为对象
- c# - 如何在 C# 的 post 方法中读取正文数据?