python - 如何使用 Python 和 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
能找到开头,中间和结尾的单词。我有一个大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
print(a.Strings.str.findall('{} |{}'.format(*b)))
推荐阅读
- c# - 如何用nuget导出文件?
- javascript - IE 无法评估第二个 if 条件 (&&)
- angular - Angular Chrome Api 数据绑定不起作用
- javascript - Javascript:如果屏幕打开,更改属性在三星上不起作用。想法如何解决?
- asp.net-core - IIS 上的 asp.net 核心延迟与 IIS express 相反
- sql - 将 Sum 除以 Count 多次优化
- git - 如何撤消在 Git 中编辑索引文件?
- cqrs - 如何存储 sagas 的数据?
- android - 为什么屏幕关闭时调用 OnStop
- python - tar.gz 使用 python 提取所有 S3