我正在尝试创建一个函数来测试两个单词是否接近或不在字符串中但我不断得到两个测试的“它们很远”,因此每个案例都是None
。
import re
nearby_words = ['daisy', 'martha']
def check_nearness(text):
word1 = nearby_words[0]
word2 = nearby_words[1]
pattern = re.compile("\b(?:"+word1+"\W+(?:\w+\W+){1,5}?"+word2+"|"+word2+"\W+(?:\w+\W+){1,5}?"+word1+")\b")
if re.match(pattern,text) is not None:
print('they are near')
else:
print('they are far')
check_nearness("daisy is near martha")
check_nearness("daisy is in this case more than five words from martha")
你可以尝试这个正则表达式:
(?:\bdaisy\b(?: +[^ \n]*){0,5} *\bmartha\b)|(?:\bmartha\b(?: +[^ \n]*){0,5} *\bdaisy\b)
这个正则表达式适用于这两种情况:
martha
来到daisy
之前daisy
来到martha
之前说明
(?:\bdaisy\b(?: +[^ \n]*){0,5} *\bmartha\b)
\b
- 一个单词边界
daisy
- 匹配daisy
\b
- 一个单词边界
(?: +[^ \n]*){0,5}
- 匹配0到5次出现的空格,后跟不是空格或换行符的字符
*
- 匹配0+出现的空格
\b
- 一个单词边界
martha
- 匹配martha
\b
- 一个单词边界|
- 或者(?:\bmartha\b(?: +[^ \n]*){0,5} *\bdaisy\b)
- 类似于上面解释的那个。刚交换了martha
和daisy
。