python - 替换缩写列表中的点?

标签 python regex python-3.x

我正在尝试删除缩写列表中的点,这样它们就不会混淆句子标记器。这应该是非常简单的。不知道为什么我的代码不起作用。

请在下面找到我的代码:

abbrevs = [
    "No.", "U.S.", "Mses.", "B.S.", "B.A.", "D.C.", "B.Tech.", "Pte.", "Mr.", "O.E.M.",
    "I.R.S", "sq.", "Reg.", "S-K."
]



def replace_abbrev(abbrs, text):
    re_abbrs = [r"\b" + re.escape(a) + r"\b" for a in abbrs]

    abbr_no_dot = [a.replace(".", "") for a in abbrs]

    pattern_zip = zip(re_abbrs, abbr_no_dot)

    for p in pattern_zip:
        text = re.sub(p[0], p[1], text)

    return text

text = "Test No. U.S. Mses. B.S. Test"

text = replace_abbrev(abbrevs, text)

print(text)

这是结果。什么都没发生。什么问题?谢谢。

 Test No. U.S. Mses. B.S. Test

最佳答案

re_abbrs = [r"\b" + re.escape(a)  for a in abbrs]

你需要使用这个。之后没有\b。这给出了正确的输出。

未测试美国 Mses BS 测试

关于python - 替换缩写列表中的点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54683211/

相关文章:

python - 在Scrapy中创建可编辑的CrawlSpider规则

regex - R:找到字符串中的最后一个点

Java Pattern 类 - 使用哪个正则表达式来从外括号获取字符串?

python-3.x - 名称 'split' 未定义问题

python - hadoop中的数据沿袭报告

python - matplotlib 中文本的部分着色

regex - Powershell - 函数匹配 - 返回时获得额外的真/假

python - Image.fromarray 不能与 array.array 一起使用

python - 尝试修复类型错误: freqRolls() missing 1 required positional argument: 'sides' python

python - Numpy:连接多维和一维数组