用点代替缩写词列表?

2024-03-28 23:39:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

请在下面找到我的代码:

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

Tags: no代码textintestreforzip
2条回答
re_abbrs = [r"\b" + re.escape(a)  for a in abbrs]

你需要使用这个。那里在.之后没有\b。这将给出正确的输出。你知道吗

Test No US Mses BS Test

您可以使用mapoperator.methodcaller而不需要re,即使它是一个很棒的库。你知道吗

from operator import methodcaller

' '.join(map(methodcaller('replace', '.', ''), abbrevs))
#No US Mses BS BA DC BTech Pte Mr OEM IRS sq Reg S-K

相关问题 更多 >