python - Python 文本匹配和替换技术推荐

标签 python replace

我是 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/

相关文章:

java - 替换哈希表的最安全选择?

xml - Shell 脚本,如何使用 sed 替换 xml 文件中字符串的单个实例

css - 如何用 css 替换标签文本(没有 id)

Python-使用颜色和字体写入文件

string - 用 Velocity 模板语言替换字符串的子串

python - BeautifulSoup : Get text data from html

python - 我的 Python 代码的输出说明

Ruby 用单反斜杠替换双反斜杠

python - 如何获取系列中的索引?

python matplotlib ax.get_xticks() 无法获取当前 xtick 位置