为什么正则表达式关于芬德尔()不起作用?

2024-04-16 11:09:01 发布

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

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

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

但是,它只消除了第一个<p>之前的部分,而第一个<p>之后的所有部分都保留了下来。我应该如何改进代码,使其只返回<p></p>之间的部分? 以下是原始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>

Tags: of代码text文本importretxt密码
1条回答
网友
1楼 · 发布于 2024-04-16 11:09:01

我强烈建议您使用合适的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(' ')]

您可以通过使用非贪婪操作符来修复regex(在*操作符后面附加一个?问号):

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

但是,您很可能会遇到regex解析的其他问题,因为HTML不是一种常规语言。你知道吗

相关问题 更多 >