检查行是否为字典类型并打印数据?

2024-05-20 17:09:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有.txt文件,它装载了大量文本,但在2-3段之间有一个类似文本的字典:

somerandomtextinthisline
{"key1":"value1","key2":"value2"}
somerandomtextinthislineblasd
asbdjalsdnlasd
dasdjasdkjn
<space>

{"key1":"value1","key2":"value2"}
someranomtextaganinasdlasd
asdasd

所以我要做的是读取整个文件并从文件中获取所有'key2',然后将其粘贴到名为result.txt的文件中

我该如何编写代码


Tags: 文件文本txt字典spacekey2key1value1
2条回答

可以使用regex匹配文件中的字典:

import re
import ast
data = [i.strip('\n') for i in open('filename.txt')]
final_dicts = list(map(ast.literal_eval, [re.sub("\s+", '', i) for i in data if re.findall('\{.*?:.*?,*\}', re.sub("\s+", '', i))]))

使用^{}将其转换为字典(如果可能),并检查是否可以使用'key2'对已解析的行进行索引:

import ast

with open(filename) as fin:
    for line in fin:
         try:
             parsed = ast.literal_eval(line)
             key2 = parsed['key2']
         except Exception:
             continue
         print(key2)  # I just print it here, you probably need to write it to another file instead

相关问题 更多 >