【问题标题】:Replace whole words only including _ as word boundry [duplicate]仅替换整个单词,包括 _ 作为单词边界 [重复]
【发布时间】:2021-02-23 15:58:30
【问题描述】:

问题:如何通过将_计为单词边界来仅替换整个单词?

我有一个 DataFrame 包含这样的任意字符串:

    column1  column2
0  My World  MyWorld
1   Worldly  My_World

我还有一本字典,里面有我喜欢替换的单词:

dictionary = {"World": "Planet", "My": "Your"}

要仅替换整个单词,我将dictionary 修改如下:

dictionary = {r'\b{}\b'.format(k):v for k, v in dictionary.items()}

然后我调用替换函数:

dataframe.replace(to_replace=dictionary, regex=True, inplace=True)

调试的完整代码在这里:

import pandas as pd

data = {'column1': ['Hello World', 'Worldly'],
        'column2': ['myWorld', 'My_World_']
       }

dataframe = pd.DataFrame(data)

dictionary = {"World": "Planet", "My": "Your"}
dictionary = {r'\b{}\b'.format(k):v for k, v in dictionary.items()}

dataframe.replace(to_replace=dictionary, regex=True, inplace=True)

print(dataframe)

结果如下:

       column1   column2
0  Your Planet   myWorld
1      Worldly  My_World

问题:字符串My_World应该替换为Your_Planet

无效的解决方案:像这样将_ 添加到正则表达式中:

dictionary = {r'(\b|_){}(\b|_)'.format(k):v for k, v in dictionary.items()}

然后单词被正确找到,由_在过程中被替换:

       column1   column2
0  Your Planet   myWorld
1      Worldly  MyPlanet

【问题讨论】:

  • 这样的东西有用吗? dictionary = {r'(\b|_){}(\b|_)'.format(k):'\\1{}\\2'.format(v) for k, v in dictionary.items()}

标签: python python-3.x regex pandas


【解决方案1】:

您可以将 _ 添加到 \b 并带有反向引用:

df.replace({r'(\b|_)({})(\b|_)'.format(k): r'\1{}\3'.format(v) 
            for k, v in dictionary.items()},
           regex=True, inplace=True)

输出:

       column1      column2
0  Your Planet      MyWorld
1      Worldly  Your_Planet

【讨论】:

    猜你喜欢
    • 2015-10-20
    • 2019-10-28
    • 2020-06-03
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多