【问题标题】:How to check if two words are next to each other in Python?如何在 Python 中检查两个单词是否相邻?
【发布时间】:2018-02-16 20:19:18
【问题描述】:

我正在尝试创建一个函数来测试两个单词是否接近或不在一个字符串中,但是对于两个测试我都得到“它们很远”,所以每个案例都是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")

【问题讨论】:

  • 您如何定义亲近度?您是否考虑过使用编辑距离/Levenshtein 距离?
  • 似乎 OP 对分隔两个感兴趣的单词的字面数(或字符)感兴趣......我在这个假设中错了吗?如果您对两个单词的相似性感兴趣,那么 Levenshtein 距离将是一个很好的起点(以及模糊的 Python 库)
  • 您的正则表达式字符串不正确,您应该使用单引号和r。试试r'\b(?:'+word1+r'\W+(?:\w+\W+){1,5}?'+word2+r'|'+word2+r'\W+(?:\w+\W+){1,5}?'+word1+r')\b'
  • @pault 含糊不清,rahlf23 是正确的,我的意思是两个词之间的词数

标签: python regex


【解决方案1】:

你可以试试这个正则表达式:

(?:\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

【讨论】:

    猜你喜欢
    • 2021-09-18
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    • 2013-02-09
    • 2019-11-07
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多