【问题标题】:How to find the first occurence of a number+word combo after a particular string?如何在特定字符串之后找到第一次出现的数字+单词组合?
【发布时间】:2021-08-05 09:06:19
【问题描述】:

我有一个字符串,它本质上是一个页面的文本。

示例是:“最终,饼干耳垢 12 以及阅读时间:最多 15 分钟”。

我要提取的是在子字符串“阅读时间”之后第一次出现“2 位数字 + 分钟”。我的字符串要大得多,并且到处都有一些数字,所以我想使用正则表达式来执行此操作,但我不确定如何从这里开始。

示例:

输入:“最终,饼干耳垢 12 以及阅读时间:最多 15 分钟”

输出:“15 分钟”

【问题讨论】:

  • 可以对字符串str.partition('Reading Time')进行分区,然后使用正则表达式

标签: python regex string


【解决方案1】:

这是一行:

print(s[s.find("Reading Time") + s[s.find("Reading Time") : len(s)].find("minutes") - 3 : s.find("Reading Time") + s[s.find("Reading Time") : len(s)].find("minutes") + 7])

【讨论】:

    【解决方案2】:

    这与正则表达式有点不同,但为什么不利用更强大的自然语言处理 Python 库来实现呢?

    这是 spaCy 的 Matcher 的示例(如果您接受额外的依赖项,https://spacy.io/usage/rule-based-matching 应该比正则表达式更灵活且易于使用):

    import spacy
    from spacy.matcher import Matcher
    
    nlp = spacy.load("en_core_web_sm")
    matcher = Matcher(nlp.vocab)
    
    pattern = [{"LOWER": "reading"}, # we require 'reading time' to be in the pattern
               {"LOWER": "time"},
               {"OP": "*"}, # there may be some stuff (optionally)
               {"LIKE_NUM": True}, # then we look for a number and 'minutes'
               {"LOWER": "minutes"}]
    
    matcher.add("duration", [pattern])
    
    # some tests, and just two of them should give in output something
    tests = ["Ultimately, biscuits earwax 12 as well as Reading Time: up to 15 minutes",
             "I wonder if this will take a reading time of more than 15 or 17 minutes in the end",
             "Will it take us more than 50 minutes?",
             "I don't have anything like 'reading time'",
             "spaCy rocks!"]
    
    # print results for each example
    for test in tests:
      doc = nlp(test)
      matches = matcher(doc)
      for match_id, start, end in matches:
        print(doc[end-2:end]) # just get the final two tokens
    

    通过调整pattern,您应该可以根据自己的需要匹配句子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2012-01-06
      • 2011-03-14
      • 1970-01-01
      • 2017-12-17
      相关资源
      最近更新 更多