[英]how to increment a whole word match in python using a variable in the regex
我試圖顯示使用python和regex在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文件中,我有'喜歡'和'愛'的字樣,所以positive_counter應該等於2 ..我如何使用單詞作為變量而不是'喜歡'? 這現在有效但只是不知道如何合並變量詞
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
只需循環文本中的所有單詞。
從正則表達式的角度來看,這應該工作:
re.search(r'\b(I|like|and|love|green|grass)\b', positive_words)
要從你的文本變量構建re(注意,我是從內存編寫的,你可能需要稍微調整一下):
regex = r'\b(%s)\b' % "|".join(words)
re.search(regex, positive_words)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.