如何使用 plural/singular 字符串替换文本

How do I use text replace with plural/singular strings

我正在尝试使用 text.replace() 替换字符串中的单词。 在使用复数替换单词之前效果很好,如下所示:

def replacing():
    texter = []
    del texter[:]
    repl = ['diabetes', 'mellitus', 'dm', ]
    it = ''
    try:
        it = iter(np.array(repl))
    except:
        pass
    txt = "tell me if its can also cause coronavirus"

    for i in range(len(np.array(repl1))):
        try:
            p = it.__next__()
            x = txt.replace("its", p)
            texter.append(x)
            x = txt.replace("it", p)
            texter.append(x)
            xxx = txt.replace("them", p)
            texter.append(xxx)
            xxxx = txt.replace("the same", p)
            texter.append(xxx)
            xxxxx = txt.replace("this", p)
            texter.append(xxx)
        except StopIteration:
            break
    mm = list(OrderedDict.fromkeys(texter))
    print (mm)

replacing()

这是这段代码的结果:

['tell me if diabetes can also cause coronavirus', 'tell me if diabetess can also cause coronavirus', 'tell me if mellitus can also cause coronavirus', 'tell me if mellituss can also cause coronavirus', 'tell me if dm can also cause coronavirus', 'tell me if dms can also cause coronavirus']

注意拼写错误的单词被替换为 'diabetess' 而不是 'diabetes','mellituss' 而不是 mellitus 和 'dms' 而不是 'dm'。

我记下了关键字 'it and its',因为相似最终会带来错误。

我怎样才能避免这种情况

问题是您要分别替换“it”和“its”。 txt.replace("it", p) 创建了一个 txt 的副本,其中“it”被 p 替换,因此“its”变成了“diabetess”。使用 re 模块指定要替换“it”或“its”。你的 for 循环看起来像这样:

for i in range(len(np.array(repl))):
        try:
            p = it.__next__()
            x = re.sub("its|it", p, txt)
            texter.append(x)
            xxx = txt.replace("them", p)
            texter.append(xxx)
            xxxx = txt.replace("the same", p)
            texter.append(xxx)
            xxxxx = txt.replace("this", p)
            texter.append(xxx)
        except StopIteration:
            break