gpt4 book ai didi

python - 如何在Python中检查两个单词是否相邻?

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:45 25 4
gpt4 key购买 nike

我正在尝试创建一个函数来测试两个单词是否在字符串中接近或不在字符串中,但对于这两个测试,我不断收到“他们很远”,因此每种情况都是 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)

<强> Click for Demo

此正则表达式适用于这两种情况:

  • 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) - 与上面解释的类似。刚刚交换了 marthadaisy

关于python - 如何在Python中检查两个单词是否相邻?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48834270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com