在replace函数中添加regex

2024-09-27 23:27:39 发布

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

我想删除函数中短语'Thank you'/'thank u'/'thanks!'... ect的所有形式(小写/大写,缩写..)。你知道吗

我目前只是做努力匹配哪项工作,但有没有更有效的方法来做这件事?你知道吗

df.text_col.replace(to_replace='Thank you',value='',inplace=True,regex=True)
df.text_col.replace(to_replace='thank you',value='',inplace=True,regex=True)
df.text_col.replace(to_replace='th(.+)u',value='',inplace=True,regex=True)
                                   .
                                   .

Tags: to函数textyoutruedfvaluecol
1条回答
网友
1楼 · 发布于 2024-09-27 23:27:39

我建议列举所有你想摆脱的thank you案例:

thanks_to_delete = '|'.join(['thanks', 'thank you'])

然后使用以下一个衬垫进行不区分大小写的替换:

df.text_col.str.replace(thanks_to_delete, '', case=False)

测试:

df=pd.DataFrame({
     'text_col': ['Thank you very much for your patience',
                  'I would just want to thank you for your patience',
                  'Thanks for your patience']
                })

df.text_col.str.replace(thanks_to_delete, '', case=False)
0                very much for your patience
1    I would just want to  for your patience
2                          for your patience
Name: text_col, dtype: object

相关问题 更多 >

    热门问题