如何计算字符串中单词或word_group出现的次数(词组)

时间:2019-04-29 04:42:05

标签: python-3.x string-matching

我在 dataframe(D1)的列中有关键字,它们是1克,2克,在某些情况下也是3克。我需要在另一个 dataframe(D2)列中搜索这些具有短语的克,并计算n-gram的出现,以便为它们提供一定的权重。

我尝试使用嵌套循环,但是它的计算量太大,而且我得到的结果也令人失望,单个字符(例如'a''in')也得到了匹配。

word_list = data['Words'].values.tolist() #converting the keywords into a list
s = pd.Series({w: pos_phrases.Phrases.str.contains(w, flags=re.IGNORECASE).sum() for w in word_list})  

短语在短语下的pos_phrases中。一些关键字是:

  

“高保真”,“高保真”,“外科手术”,“直发”,“真实”,“目标不灵敏”,“标记范围宽”等。

短语就像两个人之间的对话。例如

  

示例短语:“你好,晚上好,你好吗,你能指出导致多此一晚的事实吗?”
  要匹配的关键字:“晚上好”,“事件多”,“事件”

此处,“事件”必须 匹配,因为它是“事件”的一部分。但是,它越来越匹配。我希望我能解释我的要求。

1 个答案:

答案 0 :(得分:1)

一种干净,简单的管理方法是使用regular expressions,如下所示:

import re

Phrase = "Hello Good evening, how are you, so can you point out the facts which lead to this eventful night"
Words = "Good evening, eventful, event"

word_list = Words.split(', ')

for word in word_list:
    pattern =  r"\b" + word + r"\b" 
    matches = re.finditer(pattern, Phrase, re.MULTILINE | re.IGNORECASE)
    print(word, ': ', len([match.group() for match in matches]))  

Output:  
## Good evening :  1
## eventful :  1
## event :  0  
相关问题