【问题标题】:How to extract multiple strings using Regex?如何使用正则表达式提取多个字符串?
【发布时间】:2021-03-09 04:53:53
【问题描述】:

我在 df 中有一列包含以下值:

>>> import pandas as pd
>>> df = pd.DataFrame({'Sentence':['his is the results of my experiments KEY_abc_def KEY_mno_pqr KEY_blt_chm', 'I have researched the product KEY_abc_def, and KEY_blt_chm as requested', 'He got the idea from your message KEY_mno_pqr']})
>>> df
                                                Sentence
0       This is the results of my experiments KEY_abc_def KEY_mno_pqr KEY_blt_chm
1  I have researched the product KEY_abc_def, and KEY_blt_chm as requested
2            He got the idea from your message KEY_mno_pqr

我想使用正则表达式将 KEY 提取到没有实际“KEY_”的新列中。对于超过 1 个 KEY 的句子,应该用逗号连接。输出应该如下:

>>> df
                                                Sentence                               KEY
0      This is the results of my experiments KEY_abc_def KEY_mno_pqr KEY_blt_chm    abc_def, mno_pqr, blt_chm
1  I have researched the product KEY_abc_def, and KEY_blt_chm as requested          abc_def, blt_chm     
2           He got the idea from your message KEY_mno_pqr                           mno_pqr  

我尝试使用此代码,但它不起作用。任何建议将不胜感激。

我目前只使用第一个 KEY 的代码,而忽略了其余部分。我是正则表达式的新手,所以任何建议都将受到高度赞赏。

df['KEY']= df.sentence.str.extract("KEY_(\w+)", expand=True)

【问题讨论】:

  • 我敢打赌,无论你想做什么,ANTLR 都是一种更好的方法

标签: python regex


【解决方案1】:

使用

df['KEY']= df.sentence.str.findall("KEY_(\w+)").str.join(",")

Series.str.findall 查找捕获的子字符串的所有匹配项,str.join(",") 将结果连接成一个逗号分隔的字符串值。

熊猫测试:

>>> df['KEY']= df['Sentence'].str.findall("KEY_(\w+)").str.join(",")
>>> df
                                                                   Sentence                      KEY
0  his is the results of my experiments KEY_abc_def KEY_mno_pqr KEY_blt_chm  abc_def,mno_pqr,blt_chm
1   I have researched the product KEY_abc_def, and KEY_blt_chm as requested          abc_def,blt_chm
2                             He got the idea from your message KEY_mno_pqr                  mno_pqr

(如果您不知道,请注意:我使用pd.set_option('display.max_colwidth', None) 显示列中的所有数据,请参阅How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 2016-01-02
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多