2017-11-20 2 views
-1

私はこの次のHTMLテーブルを持っているテキストファイル(.txt)で:HTMLテキストをCSVに変換するには?

<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 
+1

あなたは解析することが困難になるだろう ''

ブロックの開始と終了が欠落している必要がありHTML。 –

答えて

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]) 
関連する問題