Python 返回列中存在的多个单词的计数

Python 返回列中存在的多个单词的计数,python,string,pandas,Python,String,Pandas,我有一个如下的熊猫数据框,列名为“text” texts throne one bar one foo two bar three foo two bar two foo one foo three one three 我想计算每一行中三个单词‘一’、‘二’和‘三’的出现情况,并返回这些单词的匹配计数(如果它是一个完整的单词)。输出如下所示 texts counts throne one 1 bar one 1 foo two 1

我有一个如下的熊猫数据框,列名为“text”

texts
throne one
bar one
foo two
bar three
foo two
bar two
foo one
foo three
one three
我想计算每一行中三个单词‘一’、‘二’和‘三’的出现情况,并返回这些单词的匹配计数(如果它是一个完整的单词)。输出如下所示

    texts   counts
    throne one  1
    bar one     1
    foo two     1
    bar three   1
    foo two     1
    bar two     1
    foo one     1
    foo three   1
    one three   2
您可以看到,相对于第一行,计数为1,因为“宝座”不被视为正在搜索的值之一。“一”不是一个完整的单词,而是“宝座”


这方面有什么帮助吗?

通过将
单词
'|'

words = 'one two three'.split()

df.assign(counts=df.texts.str.count('|'.join(words)))

        texts  counts
0  throne one       2
1     bar one       1
2     foo two       1
3   bar three       1
4     foo two       1
5     bar two       1
6     foo one       1
7   foo three       1
8   one three       2

为了确定
“宝座”
,如在“不计算”中,我们可以在正则表达式中添加一些单词边界

words = 'one two three'.split()

df.assign(counts=df.texts.str.count('|'.join(map(r'\b{}\b'.format, words))))

        texts  counts
0  throne one       1
1     bar one       1
2     foo two       1
3   bar three       1
4     foo two       1
5     bar two       1
6     foo one       1
7   foo three       1
8   one three       2

对于天赋,使用Python3.6中f字符串的原始形式

words = 'one two three'.split()

df.assign(counts=df.texts.str.count('|'.join(fr'\b{w}\b' for w in words)))

        texts  counts
0  throne one       1
1     bar one       1
2     foo two       1
3   bar three       1
4     foo two       1
5     bar two       1
6     foo one       1
7   foo three       1
8   one three       2

@MattR
one-three
的计数为2,因为我最初搜索的是
one
two
three
。在最后一行中,两个值都存在。所以它正确地给出了第2行的计数,而不应该给出第2行的计数,因为我只是在寻找完整的单词<代码>宝座是另一个词,不能作为
一个词来考虑
非常感谢。它完全符合我的要求。我会接受这个答案。