如何解决使用python清理.txt文件中的HTML并将其转换为csv应该非常简单,但我是新手
好的,在这里对我好一点。我已经累计编码了大约48小时(coding)
我的文件夹充满了完全相同的.txt文件(例如,值有所不同,但格式完全相同)。它们中的文本如下所示:
<html><head></head><body><html><head></head><body>{"Flashpoint Swindon":{"count":3,"capacity":88,"lastUpdated":"Last updated: now (4:49 PM)"},"Oakwood":{"count":45,"capacity":75,"Big Depot Leeds":{"count":32,"capacity":105,"Depot Birmingham":{"count":45,"capacity":180,"Depot Climbing Sheffield":...}}</body></html>
每个文件中有43条记录。文本文件的开头和结尾都有HTML标记。
我的最终目标是一个csv文件,其中包含如下所示的所有日期的信息:
+----------+--------------------+-------+-----------+--------+
| Date | Centre | Count | Capacity | Time |
| 20200822 | Flashpoint Swindon | 3 | 88 | 19:07 |
| 20200822 | Oakwood | 45 | 75 | 18:11 |
| 20200822 | Big Depot Leeds | 32 | 105 | 20:20 |
+----------+--------------------+-------+-----------+--------+
文件名提供了日期信息(例如2020-08-22-17-49-40_capacity.txt)。所以所有信息都在那里,我只是不知道如何完成从A到B的获取。
到目前为止,我已经编写了将文本文件清理为可以用作csv的文件的方法:
import re
my_file = open("2020-08-22-17-49-40_capacity","r+")
text = my_file.read()
text = re.sub('<html><head></head><body>','',text)
text = re.sub('</body></html>',text)
text = re.sub('},','\n',text)
text = re.sub('{',text)
text = re.sub('}}',text)
text = re.sub(':',text)
print(text)
import sys
stdoutOrigin=sys.stdout
sys.stdout = open("cleaned.txt","w")
这似乎正常,这就是文本的最终外观:
"Flashpoint Swindon","count","capacity",88,"lastUpdated","Last updated,1 hour ago (7,07 PM)"
"Oakwood",75,2 hours ago (6,11 PM)"
"Big Depot Leeds",11,105,1 min ago (8,20 PM)"
"Depot Birmingham",8,180,20 PM)"
"Depot Climbing Sheffield"...
输出有点气质-有时可以正常工作,有时会吐出空白的.txt文件。我不知道为什么。
我知道我在这里寻求巨大的帮助,但是如果任何人都可以为我所做的部分工作提供帮助,那将是惊人的。
非常感谢。
解决方法
如评论中所述,使用BeautifulSoup解析HTML /输入文件并将'body'读取为json。
将时间转换为日期时间对象,因此可以使用它进行计算和/或正确设置其格式:
import re
import csv
import json
import datetime as dt
from bs4 import BeautifulSoup
now = dt.date.today()
data = """<html><head></head><body>{"Flashpoint Swindon":{"count":0,"capacity":88,"lastUpdated":"Last updated: 1 hour ago (7:07 PM)"},"Oakwood":{"count":0,"capacity":75,"lastUpdated":"Last updated: 2 hours ago (6:11 PM)"},"Big Depot Leeds":{"count":11,"capacity":105,"lastUpdated":"Last updated: 1 min ago (8:20 PM)"},"Depot Birmingham":{"count":8,"capacity":180,"lastUpdated":"Last updated: 1 min ago (8:20 PM)"}}</body></html>"""
soup = BeautifulSoup(data,'html.parser')
content = json.loads(soup.body.text)
with open('test.csv','w') as csvfile:
writer = csv.writer(csvfile,delimiter=";")
writer.writerow(["Date","Centre","Count","Capacity","Time"]) # write headers
for item in content:
# parse the time and create a datetime object
_time = re.search(r"\((.*)\)",content[item]['lastUpdated']).groups()[0]
_timeObj = dt.datetime.strptime(_time,"%I:%M %p")
writer.writerow([now,item,content[item]['count'],content[item]['capacity'],_timeObj.strftime('%H:%M')])
print(open('test.csv').read())
输出:
Date;Centre;Count;Capacity;Time
2020-08-23;Flashpoint Swindon;0;88;19:07
2020-08-23;Oakwood;0;75;18:11
2020-08-23;Big Depot Leeds;11;105;20:20
2020-08-23;Depot Birmingham;8;180;20:20
,
虽然可接受的答案有效-但出于两个原因,我想提出这种选择: 首先,用regex解析html并不是一个好主意-到处搜索,关于它的讨论很多。因此通常最好使用html解析器。其次,实际数据为json格式,因此最好将其加载到pandas中并另存为csv。
所以不考虑dt格式等。我会做这样的事情:
import lxml.html as lh
import json
import pandas as pd
events = """[your html]"""
doc = lh.fromstring(events)
jst= json.loads(doc.xpath('//body/text()')[0])
df = pd.DataFrame(jst)
df
输出(请格式化)
Flashpoint Swindon Oakwood Big Depot Leeds Depot Birmingham
count 0 0 11 8
capacity 88 75 105 180
lastUpdated Last updated: 1 hour ago (7:07 PM) Last updated: 2 hours ago (6:11 PM) Last updated: 1 min ago (8:20 PM) Last updated: 1 min ago (8:20 PM)
然后您可以使用以下命令将其保存到csv:
df.transpose().to_csv()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。