我正在尝试解析python中的字符串以提取值。我们知道字符串可以像这样格式化变量:
food = {'fruit':'apple', 'vegetable':'carrot'}
sentence = "I ate a {fruit} and a {vegetable} today".format(**food)
有没有办法做相反的事情?从已知文本模板中提取值?就像是:
food = sentence.extract("I ate a {fruit} and a {vegetable} today")
# food gets set as dictionary {'fruit':'apple', 'vegetable':'carrot'}
理想情况下,寻找一个不错的单行代码可以在不使用自定义函数的情况下放入lambda表达式。我目前正在做2,但我觉得应该有更好的方法。
您正在描述的基本用法parse
:
>>> from parse import parse
>>> sentence = 'I ate a apple and a carrot today'
>>> template = 'I ate a {fruit} and a {vegetable} today'
>>> parse(template, sentence).named
{'fruit': 'apple', 'vegetable': 'carrot'}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句