Python使用字典用格式填充字符串
假设我有模板要用dict中的值填充: 我有这样的模板:Python使用字典用格式填充字符串,python,dictionary,format,zip,itertools,Python,Dictionary,Format,Zip,Itertools,假设我有模板要用dict中的值填充: 我有这样的模板: templates = [ "I have four {fruit} in {place}", "I have four {fruit} and {grain} in {place}", ... ] my_dict = {'fruit': ['apple', 'banana', 'mango'], 'place': ['kitchen', 'living room'], '
templates = [
"I have four {fruit} in {place}",
"I have four {fruit} and {grain} in {place}",
...
]
my_dict = {'fruit': ['apple', 'banana', 'mango'],
'place': ['kitchen', 'living room'],
'grain' : ['wheat', 'rice']
}
sentence = "I have four apple in kitchen"
{'fruit': 'apple', 'place': 'kitchen'}
有了这样的字典:
templates = [
"I have four {fruit} in {place}",
"I have four {fruit} and {grain} in {place}",
...
]
my_dict = {'fruit': ['apple', 'banana', 'mango'],
'place': ['kitchen', 'living room'],
'grain' : ['wheat', 'rice']
}
sentence = "I have four apple in kitchen"
{'fruit': 'apple', 'place': 'kitchen'}
假设我有这样一句话:
templates = [
"I have four {fruit} in {place}",
"I have four {fruit} and {grain} in {place}",
...
]
my_dict = {'fruit': ['apple', 'banana', 'mango'],
'place': ['kitchen', 'living room'],
'grain' : ['wheat', 'rice']
}
sentence = "I have four apple in kitchen"
{'fruit': 'apple', 'place': 'kitchen'}
给出这个句子、模板和字典,
我想知道这个句子匹配了其中一个模板和返回值,它匹配如下:
templates = [
"I have four {fruit} in {place}",
"I have four {fruit} and {grain} in {place}",
...
]
my_dict = {'fruit': ['apple', 'banana', 'mango'],
'place': ['kitchen', 'living room'],
'grain' : ['wheat', 'rice']
}
sentence = "I have four apple in kitchen"
{'fruit': 'apple', 'place': 'kitchen'}
与上述类似,如果:
Input: "I have four apple and wheat in kitchen"
Output: {'fruit': 'apple', 'grain': 'wheat', 'place': 'kitchen'}
如果它也能处理好这件事,那就太好了:
Input: "I have four apple in bedroom"
Output: {'fruit': 'apple'}
请注意,它只返回水果,而不返回卧室,因为卧室不在place的值中 将格式化字符串转换为正则表达式:
import re
words = {k: '(?P<{}>{})'.format(k, '|'.join(map(re.escape, v))) for k, v in my_dict.items()}
patterns = [re.compile(template.format(**words)) for template in templates]
这是一种非常快速的O(N)方法来精确匹配句子:
>>> import re
>>> templates = [
... "I have four {fruit} in {place}",
... "I have four {fruit} and {grain} in {place}",
... ]
>>> my_dict = {'fruit': ['apple', 'banana', 'mango'],
... 'place': ['kitchen', 'living room'],
... 'grain' : ['wheat', 'rice']
... }
>>> def find_matches(sentence):
... for pattern in patterns:
... match = pattern.match(sentence)
... if match:
... return match.groupdict()
...
>>> find_matches("I have four apple in kitchen")
{'fruit': 'apple', 'place': 'kitchen'}
>>> find_matches("I have four apple and wheat in kitchen")
{'fruit': 'apple', 'grain': 'wheat', 'place': 'kitchen'}
如果需要模板匹配部分句子,请将可选部分包装在(?…)
组中:
"I have four {fruit} in (?{place})"
或者将
\w+
添加到单词列表(除了有效单词之外),然后在匹配后根据my_dict
验证groupdict()
结果。例如,对于卧室中的案例,\w+
将与卧室中的部分匹配,但在位置的my_dict
列表中找不到。您自己做了什么来尝试解决此问题?使用itertools.product获得所有组合并使用.format(**{combination})填写,但不确定如何获取之后填写的键