繁体   English   中英

如何使用 Python 和 re 从字符串中提取准确的单词?

[英]How to extract exact words from a string using Python and re?

数据样本为:

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中有两个词(阶段)。 我想在一个中找到它们。 我想找到确切的单词,而不是子字符串。 所以,我希望结果是:

['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']))

我希望s能找到开头、中间和结尾的词。 我有一个很大的ab 所以我不能在这里只使用真正的字符串。 但结果是:

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

print(a.Strings.str.findall('{} |{}'.format(*b)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM