【问题标题】:Finding similar patterns in text using Python 3.7使用 Python 3.7 在文本中查找相似模式
【发布时间】:2020-10-15 20:12:16
【问题描述】:

我有一组文本模式(关键字),我的目标是在 HTML 文本中找到相似且合适的词,并使用 python 3.7 将它们收集到一个列表中。例如,如果我给定的一组模式是:{"banana", "my-apple", "(orange)", "big grapes"} 我想在 HTML 文本中查找单词,例如:"banana", “我的苹果”、“我的苹果”、“(橙色)”、“大葡萄”、“大葡萄”、“香蕉”等等。最好的方法是什么?我考虑过使用正则表达式库,但无法完全按照我的意愿找到单词。

我当前的代码是:

import re

def find_patterns_in_text(keywords, html_text):
   output_list = []
      for keyword in keywords:
         if re.findall(keyword, html_text):
            output_list.append(keyword)
   return output_list

我的代码运行不好是因为找不到以下情况:

  • 如果 HTML 文本或关键字集中的单词旁边带有某种特殊字符,则无法识别。
  • 如果其中一个关键字包含“-”而不是“”或以类似的方式包含“”而不是“-”并且在 HTML 文本中出现相同的单词但“”和“-”不合适,它不认识

【问题讨论】:

    标签: python regex


    【解决方案1】:

    转义您搜索的模式并在结果表达式中用[\s-]+ 模式替换- 和空格。

    Python code:

    import re
    
    def find_patterns_in_text(keywords, html_text):
       output_list = []
       for keyword in keywords:
           if re.search(r"(?<!\w)" + re.sub(r'(?:\\[ -])+', r'[\\s-]+', re.escape(keyword)) + r"(?!\w)", html_text, re.I):
               output_list.append(keyword)
       return output_list
    
    keys = ["banana", "my-apple", "(orange)", "big grapes", "medicine", "biotechnology"]
    string = 'banana", my-apple, my apple, (orange), big-grapes, banana, Medicine. Biotechnologyyy'
    print(find_patterns_in_text(keys, string))
    

    结果:['banana', 'my-apple', '(orange)', 'big grapes', 'medicine']

    re.search(re.sub(r'(?:\\[ -])+', r'[\\s-]+', re.escape(keyword)), html_text, re.I) 代码完成了大部分工作。 re.escape(keyword) 在特殊字符前面加上反斜杠,以便 ( 可以匹配文字括号等。由于字符串已经转义,所有空格和连字符都在前面加上反斜杠,因此 re.sub(r'(?:\\[ -])+', r'[\\s-]+', ...) 用于替换所有序列一个或多个反斜杠 + 带有 [\s-]+ 模式的空格或连字符。它将在随后对re.search 的调用中匹配空格或连字符。由于(?&lt;!\w) 前缀和(?!\w) 后缀,匹配的关键字必须是一个完整的单词。 re.search(..., html_text, re.I) 对整个字符串执行部分不区分大小写的正则表达式搜索。

    【讨论】:

    • 它不能很好地工作,即使同一个词出现在关键字和它无法识别的文本中。
    • 例如,如果关键字是:["medicine"] 并且 HTML 文本是:"Medicine"。或者另一个例子:关键字是:["biotechnology"],文本是:Biotechnology risk
    • @AviFerdman 如果搜索必须不区分大小写,请使用re.Ire.search(re.sub(r'(?:\\[ -])+', r'[\\s-]+', re.escape(keyword)), html_text, re.I)。见this Python code
    • 我将文本和关键字都转换为小写,因为我只能使用默认库,但是它仍然无法识别模式。
    • @AviFerdman Check the link,它有效。无需转换为小写。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多