【问题标题】:Matching an expression using ReGex ,Python使用正则表达式匹配表达式,Python
【发布时间】:2014-03-30 10:39:12
【问题描述】:

我有很多句子,尽管我会创建一个函数来单独对每个句子进行操作。所以输入只是一个字符串。我的主要目标是提取像"near blue meadows" 这样的介词之后的单词,我希望提取blue meadows
我所有的介词都在一个文本文件中。它工作正常,但我猜使用的正则表达式有问题。这是我的代码: 重新导入

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 个单词。在我的代码中,我使用 ({}) 来匹配 preps 列表,\s 后跟空格,(\d+\w+|\w+) 后跟 19th 或 hennur 之类的单词,\s\w+ 后跟空格和单词。我的正则表达式不匹配,因此出现None 错误。 为什么它不起作用?

Input.txt 文件的内容:

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

预期输出:

hennur police

【问题讨论】:

  • 您需要检查words 中的确切内容。
  • 对我有用(尽管您实际上应该得到near hennur police),因此您确实需要仔细检查Input.txt 是否正确(每行一个字)。
  • input.txt 的格式为 ['near','off','opposite'...] 等等。我已经编辑了我的问题。检查一下。
  • 文件的内容是"['near','nr','opp','opposite','behind','towards','above','off']"还是['near','nr','opp','opposite','behind','towards','above','off']? (是否加引号)
  • 输入文件不带引号.. 名为 words 的变量带双引号

标签: python regex string list


【解决方案1】:

该文件包含 Python 列表文字。使用ast.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

注意如果单词中有任何特殊字符在正则表达式中具有特殊含义,则需要re.escape

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-01
    • 2013-09-22
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多