【问题标题】:RE Match each word with a part of the patternRE 将每个单词与模式的一部分匹配
【发布时间】:2022-01-16 04:28:10
【问题描述】:

我认为最好用一个例子来说明这一点。

我有 RE 模式 choco_icecream = "(do|does) \w+ (loves|love|likes|like) (choco|chocolate) (ice-cream|icecream|ice cream)"。 我想检查example = "Does Jessica like Chocolate Icecream".lower() 是否与choco_icecream 匹配。

examplechoco_icecream 的匹配项,但我想知道example 的哪个单词对应choco_icecream 的元素。

我想要一本字典。理想的输出如下所示:{"(do|does)":"does", "\w+":"jessica", "(loves|love|likes|like)":"like", "(choco|chocolate)":"chocolate", "(ice-cream|icecream|ice cream)":"icecream"}

我怎样才能做到这一点?

【问题讨论】:

    标签: python python-3.x dictionary word python-re


    【解决方案1】:

    我认为,如果您只是稍微了解一下,连同文档一起玩,这一切都会很清楚。

    import re
    
    choco_icecream = "(do|does) (\w+) (loves|love|likes|like) (choco|chocolate) (ice-cream|icecream|ice cream)"
    example = "Does Jessica like Chocolate Icecream".lower()
    
    x = re.match(choco_icecream, example)
    print(x)
    print(x.groups())
    

    输出:

    <re.Match object; span=(0, 36), match='does jessica like chocolate icecream'>
    ('does', 'jessica', 'like', 'chocolate', 'icecream')
    

    打印整个match 对象会为您提供整个匹配项,但表达式中的每组括号都会创建一个新的“组”,并且这些组都是单独返回的。

    请注意,我修改了您的正则表达式以使名称也成为一个组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      • 2011-01-09
      • 2013-10-28
      • 1970-01-01
      相关资源
      最近更新 更多