如何使用正则表达式基于特定键提取特定字典?

时间:2019-03-06 10:19:33

标签: python regex text-processing

我有字典形式的数据,每个字典中键/值对的数量各不相同。我试图根据特定的键仅提取特定的词典(仅提取具有键“ A”,“ B”和“ C”的词典,不多也少)。

我尝试了以下代码:

// Comment-out this line
// compile 'com.google.android.gms:play-services-maps:11.0.4'

// Add this line
implementation 'com.google.android.gms:play-services-maps:16.1.0'

它似乎不起作用。

输入:

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}

1 个答案:

答案 0 :(得分:0)

正在尝试使用不同的正则表达式,到目前为止,这一功能似乎还不错:

r'({\"A\"\:[0-9]*\.?[0-9]*\,\"B\":[0-9]*\.?[0-9]*\,\"C\"\:[0-9]*\.?[0-9]*})