使用正则表达式从一行中提取名称和值



我想从一行中提取名称和变量,然后使用python中的正则表达式将它们作为键值对存储在字典中。如:

A has 50000 rupees and B has 15000 rupees.C has 7854 rupees and D has 10000 rupees

它应该看起来像{'A':50000,'B':15000,'C':7854,'D':10000}。整数不能超过5位

您可以使用以下模式:([a-zA-Z])(?=shass(d{,5}))

参见Regex Demo

代码:

import re
pattern = r'([a-zA-Z])(?=shass(d{,5}))'
text = 'A has 50000 rupees and B has 15000 rupees.C has 7854 rupees and D has 10000 rupees'
kv = {}
for key, value in re.findall(pattern, text):
kv[key] = value
print(kv)

输出:

{'A': '50000', 'B': '15000', 'C': '7854', 'D': '10000'}

最新更新