Python 如何使用正则表达式提取多个字符串?

Python 如何使用正则表达式提取多个字符串?,python,regex,Python,Regex,我在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

我在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
我想使用regex将键提取到一个新列中,而不使用实际的“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  
我尝试使用此代码,但它不起作用。如有任何建议,将不胜感激

df['KEY']= df.sentence.str.extract("KEY_(\w+)", expand=True)
我目前只使用第一个键的代码,而忽略了其余的。我是新加入regex的,所以任何建议都将不胜感激

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

Series.str.findall
查找捕获的子字符串的所有匹配项,并
str.join(“,”)
将结果合并为逗号分隔的字符串值

熊猫测试:

>>df['KEY']=df['sen句'].str.findall(“KEY”(\w+)).str.join(“,”)
>>>df
句子键
0这是我的实验结果键abc_def键mno_pqr键blt_chm abc_def,mno_pqr,blt_chm
1我已按照要求研究了产品密钥abc和密钥blt chm
2他是从你的信息中得到这个想法的

(请注意,如果您不知道:我使用了
pd.set\u选项('display.max\u colwidth',None)
来显示列中的所有数据,请参见)。

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