【问题标题】:python replace word not substringpython替换单词而不是子字符串
【发布时间】:2021-11-23 19:04:25
【问题描述】:

我想在数据框的一列中用另一个词替换一个词。这是我的python代码:

import pandas as pd
text="age engage"
df=pd.DataFrame([x.split(';') for x in text.split('\n')])
df['text'] = df[0].str.replace(r"age","âge")

当我想获得df['text']="âge engage" 时,我在stackoverflow 上找到的代码(包括这个代码)允许我获得df['text']="âge engâge"。谁能帮我改进我的代码?我的数据框中有几十个不同的词要替换,所以我想用一个简单的代码来实现不同的词。

【问题讨论】:

    标签: python string dataframe replace re


    【解决方案1】:

    试试-

    import pandas as pd
    text="age engage"
    df=pd.DataFrame([x.split(';') for x in text.split('\n')])
    df['text'] = df[0].str.replace(r"^age","âge") # the carrot indicates to only match from the start of the line
    

    结果

            0        text
    0  age engage  âge engage 
    

    您还可以查看正则表达式,这是一个很好的模式匹配网站Regex 101

    【讨论】:

    • 完美运行,如此简单!非常感谢!
    • @MGFern 如果我的回答可能对您有所帮助,请随时通过单击复选标记 (✔️) 将其标记为已接受,也可以随时使用向上的三角形进行投票。请阅读此link,了解有关接受和支持答案的更多信息。
    • 我很抱歉现在才提出这个问题,但我直到今天才发现这个问题。此代码仅适用于我替换的第一个单词,对于我尝试替换的第二个单词(例如“makes”到“make”)不会发生任何变化。我想替换几个不同的词
    • 查看 re.sub 的正则表达式。游乐场Regex101
    【解决方案2】:

    我建议使用这样的方法:

    import re
    
    text = 'age engage'
    for words in ['age']:
        if re.search(r'\b' + words + r'\b', text):
            print('{0}'.format(words).replace(r"age","âge"))
    

    输出:

    âge
    

    【讨论】:

      猜你喜欢
      • 2018-03-17
      • 2019-06-17
      • 1970-01-01
      • 2014-11-02
      • 2021-08-01
      • 2014-05-18
      • 2014-04-01
      • 2019-04-07
      相关资源
      最近更新 更多