我在文本文件(.txt)中有以下HTML表格:
<td class="det" colspan="1" width="40%">Basic EPS (Rs.)</td>
<td align="right" class="det">57.18</td>
<td align="right" class="det">48.84</td>
</tr>
<tr height="22px">
<td class="det" colspan="1" width="40%">Diluted Eps (Rs.)</td>
<td align="right" class="det">56.43</td>
<td align="right" class="det">48.26</td>
</tr>
CSV输出应如下所示:
Basic EPS (Rs.)|57.18|48.84
Diluted Eps (Rs.)|56.43|48.26
答案 0 :(得分:1)
尽管可能会使用正则表达式,但我肯定会建议您使用Python BeautifulSoup
库来提供帮助,如下所示:
from bs4 import BeautifulSoup
import csv
html = """<td class="det" colspan="1" width="40%">Basic EPS (Rs.)</td>
<td align="right" class="det">57.18</td>
<td align="right" class="det">48.84</td>
</tr>
<tr height="22px">
<td class="det" colspan="1" width="40%">Diluted Eps (Rs.)</td>
<td align="right" class="det">56.43</td>
<td align="right" class="det">48.26</td>
</tr>"""
# Add the missing surrounding HTML
html = "<table><tr>{}</table>".format(html)
soup = BeautifulSoup(html, "html.parser")
with open('output.csv', 'wb') as f_output:
csv_output = csv.writer(f_output, delimiter='|')
for tr in soup.find_all('tr'):
csv_output.writerow([td.text for td in tr.find_all('td')])
给你:
Basic EPS (Rs.)|57.18|48.84
Diluted Eps (Rs.)|56.43|48.26
您所拥有的HTML缺少封闭的<table>
<tr>
和最终</table>
标记,因此为了正确处理它,我已在处理之前添加了这些标记。
然后,您可以使用Python的csv
库将每行单元格写为输出CSV文件中正确分隔的行。
这是在Python 2.x上测试的,如果您使用的是Python 3.x,则需要使用open('output.csv', 'w', newline='')
。
或者,但不推荐:
import re
html = """<td class="det" colspan="1" width="40%">Basic EPS (Rs.)</td>
<td align="right" class="det">57.18</td>
<td align="right" class="det">48.84!!</td>
</tr>
<tr height="22px">
<td class="det" colspan="1" width="40%">Diluted Eps (Rs.)</td>
<td align="right" class="det">56.43</td>
<td align="right" class="det">48.26</td>
</tr>"""
with open('output.csv', 'wb') as f_output:
csv_output = csv.writer(f_output, delimiter='|')
tds = re.findall(r'\<td.*?\>(.*?)\<\/td\>', html)
for index in range(0, len(tds), 3):
csv_output.writerow(tds[index:index+3])