我有以下两个函数,它们在处理 ASCII 字符串时使用 re
模块能够完美运行:
import re
def findWord(w):
return re.compile(r'\b{0}.*?\b'.format(w), flags=re.IGNORECASE).findall
def replace_keyword(w, c, x):
return re.sub(r"\b({0}\S*)".format(w), r'<mark style="background-color:{0}">\1</mark>'.format(c), x, flags=re.I)
然而,他们在使用带重音字符的utf-8
编码字符串时失败了。在进一步搜索后,我发现regex
模块更适合Unicode字符串,因此我已经尝试将其移植到使用regex
,但是过去几个小时似乎没有什么作用。目前我的代码如下:
import regex
def findWord(w):
return regex.compile(r'\b{0}.*?\b'.format(w), flags=regex.IGNORECASE|regex.UNICODE).findall
def replace_keyword(w, c, x):
return regex.sub(r"\b({0}\S*)".format(w), r'<mark style="background-color:{0}">\1</mark>'.format(c), x, flags=regex.IGNORECASE|regex.UNICODE)
然而,使用带重音符号的(未规范化的)
utf-8
编码字符串时,我一直收到ordinal not in range
错误。编辑:建议的可能是重复问题:如何匹配非英语字符的正则表达式?不能解决我的问题。我想使用python
re
/regex
模块。其次,我想通过python使find
和replace
函数工作。编辑:我正在使用python 2。
编辑:如果您认为您可以帮助我使用Python 3使这两个函数工作,请告诉我。我希望能够通过我的python 2脚本调用python 3来仅使用这两个函数。