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

Check if line is a dictionary type and print the data?

我有 .txt 文件,它加载了很多文本,但在 2-3 段之间有一个类似于字典的文本:

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

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

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

的文件中

我该如何编码?

使用 ast.literal_eval 将其转换为字典(如果可能)并检查是否可以使用 '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

您可以使用正则表达式来匹配文件中的字典:

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))]))