我有以下两个函数,可以很好地使用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
模块。其次,我想让find
和replace
函数使用python工作。
编辑:我正在使用python 2
编辑:如果你觉得你可以帮助我使用Python 3使这两个函数工作,请告诉我。我希望我将能够调用python3使用这两个函数通过我的python2脚本。
我想我要去某个地方。我试图得到这个工作不使用模块re
或regex
,但普通python:
found_keywords = []
for word in keyword_list:
if word.lower() in article_text.lower():
found_keywords.append(word)
for word in found_keywords: # highlight the found keyword in the text
article_text = article_text.lower().replace(word.lower(), '<mark style="background-color:%s">%s</mark>' % (yellow_color, word))
现在,我只需要以不区分大小写的方式替换找到的关键字,然后就可以了。
请帮助我以不区分大小写的方式替换关键字的最后一步,而不使用re
或regex
,以便它适用于重音字符串。