如何使用Python和re从字符串中提取精确的单词?
数据样本为:如何使用Python和re从字符串中提取精确的单词?,python,string,match,word,findall,Python,String,Match,Word,Findall,数据样本为: a=pd.DataFrame({'Strings':['i xxx iwantto iii i xxx i', 'and you xxx and x you xxxxxx and you and you']}) b=['i','and you'] b中有两个词(阶段)。我想在a里找到他们。我想找到确切的单词,而不是子字符串。因此,我希望结果是: ['i' ,'i' ,'i'] ['and you',' and you ','
a=pd.DataFrame({'Strings':['i xxx iwantto iii i xxx i',
'and you xxx and x you xxxxxx and you and you']})
b=['i','and you']
b中有两个词(阶段)。我想在a里找到他们。我想找到确切的单词,而不是子字符串。因此,我希望结果是:
['i' ,'i' ,'i']
['and you',' and you ',' and you']
我需要计算这些单词在一个字符串中出现的次数。因此,我并不真的需要上面的列表。我把它放在这里是因为我想显示我想在字符串中找到确切的单词。以下是我的尝试:
s='r\'^'+b[0]+' | '+b[0]+' | '+b[0]+'$\''
len(re.findall(s,a.loc[0,'Strings']))
我希望<>代码>代码>可以在开始、中间和结尾找到单词。我有一个大的a
和b
。所以我不能在这里使用真正的字符串。但结果是:
len(re.findall(s,a.loc[0,'Strings']))
Out[110]: 1
re.findall(s,a.loc[0,'Strings'])
Out[111]: [' i ']
看起来只有中间的一个匹配并找到了。我不确定哪里出了错
a=pd.DataFrame({'Strings':['i xxx iwantto iii i xxx i',
'and you xxx and x you xxxxxx and you and you']})
print(a.Strings.str.findall('i |and you'))
输出
0 [i , i , i ]
1 [and you, and you, and you]
Name: Strings, dtype: object
正则表达式包含必须匹配的空格(但大多数情况下不存在),请尝试使用
\b
。酷。它起作用了。谢谢,谢谢。但这就是我现在想要的。我有一个大的列表b和数据帧a。因此,我必须使用我的问题中的方法来构建一个模式,因为我不知道需要匹配的所有单词。
print(a.Strings.str.findall('{} |{}'.format(*b)))