如何使用正则表达式提取基于特定键的特定字典?
How to extract specific dictionary based on specific keys using regex?
我有字典形式的数据,每个字典中键值对的数量各不相同。我正在尝试仅提取基于特定键的特定词典(仅提取那些具有键 "A"、"B" 和 "C" 的词典)。
我试过这段代码:
import re
pattern = re.compile(r'(\{\"A"\:(.*?\)\,\"B"\:(.*?\)\,\"C"\:(.*\)\})')
test_str = {"A":2.3,"B":3,"C":2.9},{"A":2.1,"B":33,"C":1.2,"D":9,"F":3.4},{"A":1.4,"B":3.3,"C":1.6,"G":3.2,"K":4},
{"A":4.3,"B":11,"C":93}
for match in re.findall(pattern, test_str):
print(match)
好像不行。
输入:
{"A":2.3,"B":3,"C":2.9},{"A":2.1,"B":33,"C":1.2,"D":9,"F":3.4},{"A":1.4,"B":3.3,"C":1.6,"G":3.2,"K":4},
{"A":4.3,"B":11,"C":93}
预期输出:
{"A":2.3,"B":3,"C":2.9},{"A":4.3,"B":11,"C":93}
正在尝试不同的正则表达式,到目前为止,这个似乎工作正常:
r'({\"A\"\:[0-9]*\.?[0-9]*\,\"B\":[0-9]*\.?[0-9]*\,\"C\"\:[0-9]*\.?[0-9]*})
我有字典形式的数据,每个字典中键值对的数量各不相同。我正在尝试仅提取基于特定键的特定词典(仅提取那些具有键 "A"、"B" 和 "C" 的词典)。
我试过这段代码:
import re
pattern = re.compile(r'(\{\"A"\:(.*?\)\,\"B"\:(.*?\)\,\"C"\:(.*\)\})')
test_str = {"A":2.3,"B":3,"C":2.9},{"A":2.1,"B":33,"C":1.2,"D":9,"F":3.4},{"A":1.4,"B":3.3,"C":1.6,"G":3.2,"K":4},
{"A":4.3,"B":11,"C":93}
for match in re.findall(pattern, test_str):
print(match)
好像不行。
输入:
{"A":2.3,"B":3,"C":2.9},{"A":2.1,"B":33,"C":1.2,"D":9,"F":3.4},{"A":1.4,"B":3.3,"C":1.6,"G":3.2,"K":4},
{"A":4.3,"B":11,"C":93}
预期输出:
{"A":2.3,"B":3,"C":2.9},{"A":4.3,"B":11,"C":93}
正在尝试不同的正则表达式,到目前为止,这个似乎工作正常:
r'({\"A\"\:[0-9]*\.?[0-9]*\,\"B\":[0-9]*\.?[0-9]*\,\"C\"\:[0-9]*\.?[0-9]*})