我是 python 新手,并试图找到执行匹配和替换的最佳和最有效的方法。这是我的问题。
我有一本字典,其中包含如下条目。
myDict = {'I HAVE A * NAMED *':'A <star=1> named <star=2> is cool!'}
我的目标是获得意见:
myInput = raw_input()
# Example input: I HAVE A DOG NAMED MAX
然后将此输入与 myDict 中的键进行匹配:
input: 'I HAVE A DOG NAMED *MAX*' matches with dictionary key: 'I HAVE A * NAMED *'
然后输出键值,并将星号标记替换为缺少的 myInput 单词 DOG 和 MAX。
output = 'A DOG named MAX is cool!'
非常感谢任何明智的建议!
最佳答案
这就是你想要的吗?
import re
myDict = {'I HAVE A (.+) NAMED (.+)':'A <star=1> named <star=2> is cool!'}
input="I HAVE A dog NAMED max"
for x in myDict.keys():
if re.match(x,input) :
d=myDict[x]
for n in range(1, 3):
d = d.replace('<star='+str(n)+'>',re.match(x,input).group(n))
print '=>', d
关于python - Python 文本匹配和替换技术推荐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42559596/