python - 如何使用正则表达式中的变量在 python 中增加整个单词匹配

标签 python regex variables increment

我正在尝试使用 python 和正则表达式显示 txt 文件中有多少单词匹配,但我不想使用术语“like”,而是想使用变量“words”

text = 'I like and love green grass'
positive_words = positive_words=open("positive.txt").read()

words = text.split(' ')

if re.search(r'\blike\b',positive_words):
    positive_counter=positive_counter+1
print positive_counter

在我的 txt 文件中,我有“like”和“love”这两个词,所以 positive_counter 应该等于 2.. 我如何使用词作为变量而不是“like”?这现在有效,但只是不知道如何合并可变词

最佳答案

text = 'I like and love green grass'
positive_words = positive_words=open("positive.txt").read()

words = text.split(' ')

for word in words:
    if re.search(r'\b' + word + r'\b',positive_words):
        positive_counter=positive_counter+1
print positive_counter

只是循环文本中的所有单词。

关于python - 如何使用正则表达式中的变量在 python 中增加整个单词匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38644263/

相关文章:

javascript - 像 Python 一样的 NodeJS 字符串格式?

regex - Bash 正则表达式 : Matching numbers 0-1000

r - 在R中的多个数据框中创建一个新变量

javascript - 将变量从 ForEach 传递到 addEventListener

javascript - onclick 函数中返回变量

Collat​​z 猜想的 Python 递归函数

python - 如何将现有环境克隆到anaconda中的基础环境

python - 使用 Twisted 更新共享数据

Python 正则表达式 : Including whitespace inside character range

regex - Google 表格 REGEXREPLACE 如果在中间则保留重复字符串之一,但如果在开头或结尾则删除它们