使用ReGex和Python匹配表达式

2024-04-18 19:58:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有很多句子,不过我会创建一个函数,分别对每个句子进行操作。所以输入只是一个字符串。我的主要目标是提取介词后面的单词,比如in "near blue meadows",我希望blue meadows被提取出来。
我所有的介词都在一个文本文件里。它工作的很好,但我想有一个问题,在正则表达式使用。这是我的密码: 进口re

with open("Input.txt") as f:
    words = "|".join(line.rstrip() for line in f)
    pattern = re.compile('({})\s(\d+\w+|\w+)\s\w+'.format(words))
    text3 = "003 canopy grace appt, classic royale garden, hennur main road, bangalore 43. near hennur police station"
    print(pattern.search(text3).group())

这将返回:

AttributeError                            Traceback (most recent call last)
<ipython-input-83-be0cdffb436b> in <module>()
      5     pattern = re.compile('({})\s(\d+\w+|\w+)\s\w+'.format(words))
      6     text3 = ""
----> 7     print(pattern.search(text3).group())

AttributeError: 'NoneType' object has no attribute 'group

主要的问题是regex,我的预期输出是“hennur police”,即在near后面2个单词。在我的代码中,我使用({})从prep列表中进行匹配,\s后跟空格,(\d+\w+|\w+)后跟类似19或hennur的单词,\s\w+后跟空格和单词。我的正则表达式无法匹配,因此出现None错误。 为什么不起作用?你知道吗

文件的内容:

['near','nr','opp','opposite','behind','towards','above','off']

预期输出:

hennur police

Tags: inrelinegroupblue单词句子pattern
1条回答
网友
1楼 · 发布于 2024-04-18 19:58:04

该文件包含Python list literal。使用^{}解析文本。你知道吗

>>> import ast
>>> ast.literal_eval("['near','nr','opp','opposite','behind','towards','above','off']")
['near', 'nr', 'opp', 'opposite', 'behind', 'towards', 'above', 'off']

import ast
import re

with open("Input.txt") as f:
    words = '|'.join(ast.literal_eval(f.read()))
    pattern = re.compile('(?:{})\s(\d*\w+\s\w+)'.format(words))
    text3 = "003 canopy grace appt, classic royale garden, hennur main road, bangalore 43. near hennur police station"

    # If there could be multiple matches, use `findall` or `finditer`
    #   `findall` returns a list of list if there's capturing group instead of
    #   entire matched string.
    for place in pattern.findall(text3):
        print(place)

    # If you want to get only the first match, use `search`.
    #   You need to use `group(1)` to get only group 1.
    print pattern.search(text3).group(1)

输出(第一行以for循环打印,第二行来自search(..).group(1)):

hennur police
hennur police

注意如果单词中有任何特殊字符在正则表达式中具有特殊含义,则需要^{}每个单词。你知道吗

相关问题 更多 >