【问题标题】:Replace word only if it stands alone [duplicate]仅当单词独立时才替换单词[重复]
【发布时间】:2019-10-28 23:14:52
【问题描述】:

我有一个函数,我想通过用“访客”替换一个人的名字来匿名文本。

为此,我编写了以下函数:

def replaceName(text, name):
    newText = text.replace(name, 'visitor')
    return str(newText)

我使用它来应用它:

all_transcripts['msgText'] = all_transcripts.apply(lambda x: replaceName(x['msgText'], x['nameGuest']), axis=1)

但是,如果它是另一个单词的一部分,这也会替换名称。因此,我只想替换这个词独立存在的实例。我试过" "+name+" ",但是如果名字在句子的开头或结尾,这不起作用。

此外,我考虑过:Python regular expression match whole word。但是,这里他们说如何找到这样的词,而不是如何替换它。我很难找到和更换它。

谁能帮我解决这个问题?

【问题讨论】:

    标签: python regex replace


    【解决方案1】:
    import re
    
    text = "Mark this isMark example Mark."
    
    print (re.sub(r"\bMark\b", "visitor", text))
    

    输出:

    visitor this isMark example visitor.
    

    【讨论】:

    • 编辑后的解决方案将起作用。
    猜你喜欢
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 2023-02-25
    • 2015-08-19
    • 2017-09-29
    相关资源
    最近更新 更多