【问题标题】:Why the regex with re.findall() doesn't work?为什么带有 re.findall() 的正则表达式不起作用?
【发布时间】:2017-08-27 05:31:05
【问题描述】:

我试图从 html 代码中提取文本。这是我的代码:

import re
Luna = open('D:\Python\Luna.txt','r+')
text=Luna.read()
txt=re.findall('<p>\s+(.*)</p>',text)
print txt

但是,它只消除了第一个 &lt;p&gt; 之前的部分,而第一个 &lt;p&gt; 之后的所有内容都保留了下来。我应该怎么做才能改进我的代码,使其只返回&lt;p&gt;&lt;/p&gt;之间的部分? 这是原始html代码的一部分:

src="/advjs/gg728x90.js"></script></td>  </tr></table><div class="text" align="justify"></p><p> Sure. Eye of newt. Tongue of snake.</p><p>  She added, &ldquo;Since you&rsquo;re taking Skills for Living, it&rsquo;ll be good practice.&rdquo;</p><p>  For what? I wondered. Poisoning my family? &ldquo;I have to baby-sit,&rdquo; I said, a little too gleefully.</p>

【问题讨论】:

标签: python regex findall


【解决方案1】:

强烈建议您使用合适的 HTML 解析器,例如 BeautifulSoup:

from bs4 import BeautifulSoup

soup = BeautifulSoup(Luna.read())
para_strings = (p.get_text() for p in soup.find_all('p'))
txt = [p.strip() for p in para_strings if p.startswith(' ')]

您可以使用非贪婪运算符修复您的正则表达式(在 * 运算符后附加一个 ? 问号):

txt=re.findall('<p>\s+(.*?)</p>',text)

但是,您很可能会遇到正则表达式解析的其他问题,因为 HTML 不是常规语言。

【讨论】:

    猜你喜欢
    • 2015-04-13
    • 2014-06-01
    • 1970-01-01
    • 2012-11-17
    • 2021-11-21
    • 2013-12-05
    • 2014-12-03
    相关资源
    最近更新 更多