【问题标题】:Issue with " in a findall statementfindall 语句中的 " 问题
【发布时间】:2019-05-24 12:04:29
【问题描述】:

在 python 搜索 html 源代码的正则表达式 findall 语句中,我遇到了使用 " 的问题。

我正在搜索一些 html 源代码,但似乎无法在 findall 语句中使用引号 (")。由于某些无法更改的要求,我无法使用诸如 beautifulsoup 之类的外部库来帮助搜索. 我已将变量名称更改为搜索。

from re import *

def suncorp_find():

    # Setup to find information
    suncorp_file = open('suncorp.html')
    contents_suncorp = suncorp_file.read()

    # Search the HTMl files to find the data
    suncorp_titles = findall(r"\"event-title\">(\w )+", contents_suncorp)

    print(suncorp_titles)

suncorp_find()

我希望得到一个包含项目的列表,但我只是得到一个空列表。仅搜索 event-title 时,我会使用 search_titles 列表获得多个项目。

提前感谢您的帮助

<h6 class="event-title">Queensland Reds v Jaguares</h6>

【问题讨论】:

  • 样本输入是什么?
  • 尝试引用符号:\\"event-title\\"&gt;([\w ]+)
  • 我已经添加了指向 html 源代码的链接,我也尝试了引用符号,但也没有用
  • 请在问题本身和纯文本中包含示例输入;不在图像的链接中。还包括您的预期输出。
  • 使用给定的样本输入,我得到['Queensland Reds v Jaguares']。这不是你要找的吗?

标签: python regex findall


【解决方案1】:

使用这个正则表达式:

suncorp_titles = findall(r"\"event-title\">(\w.*?)<", contents_suncorp)

或者为什么不在下面?我已删除 \w 检查。我不知道你是否真的需要它。

suncorp_titles = findall(r"\"event-title\">(.*?)<", contents_suncorp)

我接受了输入:

<h6 class="event-title">Queensland Reds v Jaguares</h6>
<h6 class="event-title">testing line two</h6>

输出:

['Queensland Reds v Jaguares', 'testing line two']

【讨论】:

  • 调试我的代码后,我发现当python出于某种原因解释它时,html文件被修改了,并且event-title变成了,我不知道为什么会这样,看起来很奇怪但感谢您的回复。
【解决方案2】:

你应该引用"符号。

from re import findall

tmp = """<some_tag name="event-title">Some text 1</some-tag>
<some_tag name="event-title">Some text 2</some-tag>
<some_tag name="event-title">Some text 3</some-tag>"""

result = findall("\"event-title\">([\w ]+)", tmp)

输出:

['Some text 1', 'Some text 2', 'Some text 3']

附:我建议您使用regex test website 来验证您的表达式。

【讨论】:

  • 这不可能是解决方案 - "\"event-title\"&gt;([\w ]+)" 与问题 '"event-title"&gt;([\w ]+)' 中使用的文字完全相同
  • 由于某种原因这不起作用,代码在正则表达式测试器中测试时有效,但在 python 中运行时它不起作用。
  • @Lachiesterling,在调用findall()之前尝试调试代码并检查contents_search的值。
  • @ChristophBurschka,是的,你是对的,我错过了他使用单引号。
  • 我已经测试了这段代码,但它不起作用,请查看上面的链接图片,它准确地显示了我正在搜索的内容
猜你喜欢
  • 1970-01-01
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 2014-09-12
  • 1970-01-01
相关资源
最近更新 更多