正则表达式能否识别形容词与动词?相关代码技术问题问询
Hey there, let's tackle these two regex questions one by one—they're great for understanding how Python's re module works under the hood!
First, let's recap the context with your code snippet:
import re sentence = 'horses are fast' regex = re.compile('(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)') matched = re.search(regex, sentence) print(matched.groupdict())
Which outputs: {'adjective': 'fast', 'verb': 'are', 'animal': 'horses'}
1. How does the regex pattern match the target sentence?
This regex relies entirely on structural pattern matching, not actual semantic understanding (a key point: it doesn't know "fast" is an adjective or "are" is a verb—it just follows position and word-format rules). Here's the step-by-step breakdown:
- The pattern is split into three named capture groups, separated by literal spaces:
(?P<animal>\w+): The(?P<name>syntax creates a named group calledanimal.\w+matches one or more word characters (letters, numbers, underscores)—here, it grabs the first word in the sentence:horses.- The first space in the regex matches the literal space between
horsesandare. (?P<verb>\w+): This named group matches the next sequence of word characters, which is the second word:are.- The second space in the regex matches the space between
areandfast. (?P<adjective>\w+): This final named group matches the last word:fast.
- As a quick test: if we rearranged the sentence to
'fast are horses', the regex would still match—but it would incorrectly labelfastasanimal,areasverb, andhorsesasadjective. That's concrete proof it doesn't care about semantic attributes, just position and word structure.
2. Does the matched object contain the regex pattern used to generate it?
Absolutely! Python's re.Match object stores a reference to the re.Pattern that created it. You can access this via the .re attribute of the match object.
To verify, add this line to your existing code:
print(matched.re.pattern)
This will output the exact regex pattern string you defined:(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)
This is super useful if you're working with multiple regex patterns and need to confirm which one produced a specific match.
内容的提问来源于stack exchange,提问作者Kelvin Baumgart

