【问题标题】:How does this word replacement function work?这个单词替换功能是如何工作的?
【发布时间】:2016-05-13 10:12:49
【问题描述】:
import re
def multiwordReplace(text, wordDic):
rc = re.compile('|'.join(map(re.escape, wordDic))))
def translate(match):
return wordDic[match.group(0)]
return rc.sub(translate, text)
这段代码是从另一个来源复制的,但我不确定它如何替换文本段落中的单词,也不明白为什么在这里使用're'函数
【问题讨论】:
标签:
python
regex
function
python-3.x
【解决方案1】:
一片一片……
# Our dictionary
wordDic = {'hello': 'foo', 'hi': 'bar', 'hey': 'baz'}
# Escape every key in dictionary with regular expressions' escape character.
# Escaping is requred so that possible special characters in
# dictionary words won't mess up the regex
map(re.escape, wordDic)
# join all escaped key elements with pipe | to make a string 'hello|hi|hey'
'|'.join(map(re.escape, wordDic))
# Make a regular expressions instance with given string.
# the pipe in the string will be interpreted as "OR",
# so our regex will now try to find "hello" or "hi" or "hey"
rc = re.compile('|'.join(map(re.escape, wordDic)))
所以 rc 现在与字典中的单词匹配,rc.sub 替换给定字符串中的那些单词。翻译函数只返回键的对应值正则表达式返回匹配项。
【解决方案2】:
-
re.compile() - 将表达式字符串编译为正则表达式对象。该字符串由worDic 的连接键和分隔符| 组成。给定一个 wordDic {'hello':'hi', 'goodbye': 'bye'} 字符串将是 'hello|hi' 可以翻译成 "hello or hi"
-
def translate(match): - 定义了一个回调函数,它将处理每一个匹配项
-
rc.sub(translate, text) - 执行字符串替换。如果正则表达式匹配文本,则通过回调在 wordDic 中查找匹配项(实际上是 wordDic 的键)并返回翻译。
例子:
wordDic = {'hello':'hi', 'goodbye': 'bye'}
text = 'hello my friend, I just wanted to say goodbye'
translated = multiwordReplace(text, wordDic)
print(translated)
输出是:
hi my friend, I just wanted to say bye
编辑
使用re.compile() 的主要优点是如果多次使用正则表达式可以提高性能。由于在每个函数调用上都会编译正则表达式,因此没有任何收获。如果wordDic 被多次使用,则为wordDic 生成一个multiwordReplace 函数,并且只编译一次:
import re
def generateMwR(wordDic):
rc = re.compile('|'.join(map(re.escape, wordDic)))
def f(text):
def translate(match):
print(match.group(0))
return wordDic[match.group(0)]
return rc.sub(translate, text)
return f
用法如下:
wordDic = {'hello': 'hi', 'goodbye': 'bye'}
text = 'hello my friend, I just wanted to say goodbye'
f = generateMwR(wordDic)
translated = f(text)