【问题标题】:Python: Exact word match using a list and data framePython:使用列表和数据框精确匹配单词
【发布时间】:2020-04-16 05:43:50
【问题描述】:

大家好 :) 希望你们一切都好。 我是 python 新手,在获取完全匹配的单词时遇到了问题。我有一个单词列表key_list,我需要使用此列表循环遍历字符串数据框df['response'],以计算来自key_list 的单词出现在数据框df['response'] 中的次数。

目前,这是我正在使用的代码:

df['count_response']=df['response'].str.count('|'.join(key_list)) 

这是我收到的输出:

key_list:  ['honestli', 'know', 'realli', 'feel', 'wast', 'time', 'school', 'good', 'reason', 'go', 'colleg', 
'howev', 'wonder', 'whether', 'continu', 'cant', 'see', 'frankli', 'care', 'less', 'understand']
              response  count_response
0          parent said             0
1     want make differ             0
2            dont know             1
3                 rich             0
4       go career want             2
5              actuari             0
6          social life             0
7       expect societi             0
8                                  0
9           help peopl             0
10   realli love learn             1
11               money             0
12       passion field             0
13  happi learn econom             0
14   want uplift peopl             0

很遗憾,这不是正确的输出。在第 4 行中,count_response 的值为 2;但是,在key_list 中只有“go”这个词。我怀疑python正在计算“care”这个词(在key_list中)并且它在“career”这个词中,但它不应该计算这个词,因为我需要一个精确的词匹配。

感谢您的宝贵时间,感谢您的回复!

【问题讨论】:

    标签: python string pandas exact-match


    【解决方案1】:

    我认为您需要\b\b 的字边界:

    df['count_response']=df['response'].str.count('|'.join(r"\b{}\b".format(x) for x in key_list))
    

    【讨论】:

    • 非常感谢!我一直在寻找 DAYS 的解决方案。非常感谢你的帮助!我真的很感激!
    猜你喜欢
    • 2019-08-09
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多