Skip to main content
 首页 » 编程设计

python之如何使用 python 从文本中提取确切的单词

2025年05月04日14Renyi-Fan

我想计算有多少行包含与我选择的关键字匹配的单词。所以我这样编码。

  28         for each_keyword in keywords: 
  29             if each_keyword in text: 
  31                 related_tweet_count += 1 
  32                 print "related_tweet_count", related_tweet_count 
  33                 print text 

表现非常好。但它有一个问题。例如,我有一个关键字“flu”,那么它不仅会给出“flu”,还会给出“influence”。为了解决这个问题,我搜索了匹配词示例并修复了这样的代码。

  28         for each_keyword in keywords: 
  30             if re.search('\beach_keyword\b', text, re.I): 
  31                 related_tweet_count += 1 
  32                 print "related_tweet_count", related_tweet_count 
  33                 print text 

但它不起作用。请帮帮我!

请您参考如下方法:

您实际上需要将 each_keyword 替换到正则表达式中。目前它实际上是在尝试匹配“each_keyword”。

28         for each_keyword in keywords: 
30             if re.search('\\b' + each_keyword + '\\b', text, re.I): 
31                 related_tweet_count += 1 
32                 print "related_tweet_count", related_tweet_count 
33                 print text