python - 用于大型 Unicode 文本的 Python 查找器或子程序
问题描述
我必须将多次出现的标记替换为大型 Unicode 文本文档。目前我正在迭代我的字典中的单词并用sub
编译的正则表达式替换:
for token, replacement in dictionary.tokens().iteritems():
r = re.compile(word_regex_unicode(token), flags=re.I | re.X | re.UNICODE)
text = r.sub(replacement, text)
我的话正则表达式就像
# UTF8 unicode word regex
def word_regex_unicode(word):
return r"(?<!\S){}(?!\S)".format(re.escape(word))
这意味着必须编译一个新的正则表达式,然后sub
对每个令牌(如果存在或不存在于文档中)进行调用text
。作为替代方法,可以使用re.finditer
查找令牌的出现,然后在找到令牌时调用re.sub
:
for token, replacement in dictionary.tokens().iteritems():
r = re.compile(word_regex_unicode(token), flags=re.I | re.X | re.UNICODE)
for m in r.finditer(token, text):
# now call sub
text = r.sub(replacement, text)
从而避免re.sub
在实际不需要时调用。最后一种方法可以使用re.finditer
组结果进行改进:
for m in r.finditer(token, text):
# match start: match.start()
index = match.start()
# replace from start to end
text = text[:index] + token + text[index + 1:]
在这些方法中,哪种方法更快?
解决方案
推荐阅读
- c++ - 如何在控制台应用程序中为文本着色?
- c# - 使用 SSH.NET SFTP 执行 sudo 以访问文件
- powershell - 如何使用 Powershell 从 json 属性中获取键值对
- java - 类文件的版本错误 55.0,应该是 52.0 (IntelliJ)
- angular - 在 Angular 组件中使用被覆盖的 SCSS 变量的正确方法
- .net - .NET 源链接:尽管链接正确,但“找不到源”
- python - 相同 x 轴值的不同条形图
- json - Kotlin 序列化对于这种类型的数据结构?
- python - 为什么 to_datetime 可以处理正时区 (UTC+) 而不是负时区 (UTC-)?
- javascript - 如何编写(flutter web)代码,以便 JavaScript 文件可以在我的本地机器上运行?