python - 用于大量搜索替换对的正则表达式替换

标签 python regex nlp text-processing

<分区>

我希望能够跨文档进行大规模搜索和替换,以实现文本规范化。

例如:

  1. 查找所有使用 U.S.AUSA 并替换为 United States Of America
  2. 找到所有和号 (&) 并替换为单词 and

我还希望能够在不更改任何代码的情况下向系统添加新规则。所以搜索替换对存储在数据存储中,这意味着任何人都可以添加、更新、删除规则。

我一直在使用 Python re 模块,它非常好,理想情况下我想将元组列表传递给子命令,然后它遍历每个元组并进行替换。除了遍历元组列表然后为每个元组创建一个正则表达式之外,是否有更好的方法来执行此操作 - 它非常缓慢且效率低下,尤其是对于大型文档:

replacements = [
  r('USA','United States Of America'),
  (r'U\.S\.A','United States Of America'),
  (r'US of A', 'United States of America')]

for replacement in replacements:
  document = re.sub(replacement[0],replacement[1],document

最佳答案

您的示例都不需要正则表达式。为什么不试试好的 ol' 字符串替换?

replacements = [
    ('USA','United States Of America'),
    ('U\.S\.A','United States Of America'),
    ('US of A', 'United States of America')]

for replacement in replacements:
    document = document.replace(replacement[0], replacement[1])

这看起来会很慢,但您应该在排除该方法之前对其进行基准测试。 Python 非常擅长此类工作,结果可能会让您大吃一惊。

如果您确实需要正则表达式,编译它们可能会带来巨大的提升:

replacements = [
    (re.compile('USA'),'United States Of America'),
    (re.compile('U\.S\.A'),'United States Of America'),
    (re.compile('US of A'), 'United States of America')]

for pattern, replacement in replacements:
    document = pattern.sub(replacement, document)

这为 Python 省去了每次使用它们时都必须重新编译这些正则表达式的工作。

如果您有时只需要正则表达式,请考虑两次遍历文档:一次使用正则表达式,一次使用字符串替换。或者,如果您需要一些特定的替换顺序,您可以使用以下内容:

replacements = [
    (re.compile('USA'),'United States Of America'),
    ('foo', 'bar'),
    (re.compile('U\.S\.A'),'United States Of America'),
    ('spam', 'eggs'),
    (re.compile('US of A'), 'United States of America')]

for pattern, replacement in replacements:
    try:
        document = pattern.sub(replacement, document)
    except AttributeError:
        document = document.replace(pattern, replacement)

关于python - 用于大量搜索替换对的正则表达式替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10703987/

相关文章:

python - 在 BaseHTTPServer 中启动守护进程

python - 用Python绘制随机游走图

python - "[Errno 13] Permission denied"仅在 Ubuntu 服务器上尝试更新/更改文档时

javascript - 这个正则表达式有什么问题?

php - 从字符串中提取启发式(模糊)日期?

python - 程序运行时,一行代码执行了多少次?

c# - 当不遵循特定字符(?)时,如何使用正则表达式匹配字符(')?

algorithm - 使用自然语言生成解读句子中的单词

machine-learning - NLP 变压器 : Best way to get a fixed sentence embedding-vector shape?

c# - 如何正确地为单词添加 "a"和 "an"前缀?