我正在解析一个HTML文件,并希望匹配两个字符序列之间的所有内容:Sent:和<br>标记。
我见过几个非常相似的问题,并尝试了他们的所有方法,但没有一个对我有用,可能是因为我是个新手,做一些非常简单的事情是错误的。
以下是我的相关代码:
for filename in os.listdir(path): #capture email year, month, day
file_path = os.path.join(path, filename)
if os.path.isfile(file_path):
with open(file_path, 'r') as f:
html = f.read()
soup = BeautifulSoup(html, 'html.parser')
a = re.findall(r'Sent:/.+?(?=<br>)/', soup.text)[0]
#a = re.findall(r'Sent:(.*)', soup.text)[0]
print(a)
d = parser.parse(a)
print("year:", d.year)
print("month:", d.month)
print("day:", d.day)我还为我的RegEx:a = re.findall(r'Sent:/^(.*?)<br>/', soup.text)[0]和a = re.findall(r'Sent:/^[^<br>]*/', soup.text)[0]尝试了这些
但我一直有个错误list index out of range..。但是,即使当我删除[0]时,也会得到行d = parser.parse(a)上的错误AttributeError: 'list' object has no attribute 'read' .只打印[]作为print(a)的结果
下面是HTML的相关块:
<b>Sent:</b> Friday, June 14, 2013 12:07 PM<br><b>To:</b> David Leveille<br><b>Subject:</b> 发布于 2017-02-16 18:29:19
问题不是真正的regex,而是BeautifulSoup解析HTML (毕竟是它的工作)并更改其内容的事实。例如,您的<br>将转换为<br/>。另一点: soup.text删除了所有的标记,这样你的正则表达式就不能再工作了。
更清楚的是,尝试这个脚本:
from bs4 import *
import re
from dateutil import parser
pattern = re.compile(r'Sent:(.+?)(?=<br/>)')
with open("myfile.html", 'r') as f:
html = f.read()
print("html: ", html)
soup = BeautifulSoup(html, 'lxml')
print("soup.text: ", soup.text)
print("str(soup): ", str(soup))
a = pattern.findall(str(soup))[0]
print("pattern extraction: ", a)对于第二部分:由于日期字符串的形式不正确(因为初始的<br/>),您应该添加参数fuzzy=True,就像在日期文件l中解释的那样。
d = parser.parse(a, fuzzy=True)
print("year:", d.year)
print("month:", d.month)
print("day:", d.day)另一个解决方案是使用更精确的正则表达式。例如:
pattern = re.compile(r'Sent:</b>(.+?)(?=<br/>)')发布于 2017-02-16 17:30:06
请您将您的regex替换为下面查找关键条款以及它们之间的任何内容的正则表达式,并告诉我您现在收到的错误是什么?
a=re.findall(r"Sent:(.*?)<br>", soup.text)[0]发布于 2017-02-16 17:47:13
尝尝这个。它还考虑到如果<br>标记包含斜杠。
/Sent:(.*?)<\/*br>/https://stackoverflow.com/questions/42280699
复制相似问题