【发布时间】:2017-11-25 00:11:46
【问题描述】:
我有一个评论列表和一个单词列表,我试图计算每个单词在每个评论中出现的次数。关键字列表大约有 30 个,并且可能会增长/更改。目前的评论数量大约为 5000 条,评论字数从 3 到几百个字不等。评论的数量肯定会增加。目前关键字列表是静态的,评论的数量不会增长太多,因此任何在每条评论中获取关键字计数的解决方案都可以工作,但理想情况下,如果评论数量急剧增加或关键字发生变化,所有评论都必须重新分析。
我一直在阅读有关 stackoverflow 的不同方法,但无法使用任何方法。我知道您可以使用skikit learn 来计算每个单词的数量,但还没有弄清楚是否有办法计算一个短语。我也尝试过各种正则表达式。如果关键字列表都是单个单词,我知道我可以很容易地使用skikit learn、循环或正则表达式,但是当关键字有多个单词时我会遇到问题。 我试过的两个链接
Python - Check If Word Is In A String
Phrase matching using regex and Python
这里的解决方案很接近,但它不计算同一单词的所有出现次数 How to return the count of words from a list of words that appear in a list of lists?
关键字和评论列表都是从 MySQL 数据库中提取的。所有关键字都是小写的。所有文本均已小写,除空格外的所有非字母数字均已从评论中删除。我最初的想法是使用skikit learn countvectorizer 来计算单词,但不知道如何计算我切换的短语。我目前正在尝试使用循环和正则表达式,但我愿意接受任何解决方案
# Example of what I am currently attempting with regex
keywords = ['test','blue sky','grass is green']
reviews = ['this is a test. test should come back twice and not 3 times for testing','this pharse contains test and blue sky and look another test','the grass is green test']
for review in reviews:
for word in keywords:
results = re.findall(r'\bword\b',review) #this returns no results, the variable word is not getting picked up
#--also tried variations of this to no avail
#--tried creating the pattern first and passing it
# pattern = "r'\\b" + word + "\\b'"
# results = re.findall(pattern,review) #this errors with the msg: sre_constants.error: multiple repeat at position 9
#The results would be
review1: test=2; 'blue sky'=0;'grass is green'=0
review2: test=2; 'blue sky'=1;'grass is green'=0
review3: test=1; 'blue sky'=0;'grass is green'=1
【问题讨论】:
-
那么你尝试了哪一个?
-
@user1767754 我尝试了上面 re.iterall 代码中显示的各种正则表达式。对于 re.findall(r'\bword\b',review) 我不确定为什么没有值被传递给变量 word