簡體   English   中英

在python中的每個記錄之后插入新行,並在記錄元素之間添加逗號

[英]Insert new line after every record in python and comma between elements of record

這是我解析html文件的代碼。 解析表后,我需要將每個記錄存儲在文件中,並且在每個記錄之后都需要換行,並且記錄中的每個元素都應該用逗號分隔。 我設法換行了,但沒有逗號。

這是我的代碼:

from BeautifulSoup import BeautifulSoup
import re
import os

OUTFILE = os.path.join('company', 'a', 'viewids')

soup = BeautifulSoup(open("/company/a/searches/a"))
rows = soup.findAll("table",{"id":"cos"})
records = []
for tr in rows:
   cols = tr.findAll('td')
   for td in cols:
    record = td.contents[0]
    records.append(record+'\n')
open(OUTFILE, 'w').writelines(records)

這是記錄:

A CONSULTING TEAM INC 1040792 7380

A J&J PHARMA CORP 1140452 9995

My output is:

A CONSULTING TEAM INC

1040792

7380

A J&J PHARMA CORP

1140452

9995

逗號分隔值

您要描述的文件格式就是CSV格式。 在Wikipedia上瀏覽並搜索“逗號分隔的值”。

使用Python,您可以使用csv包。 轉到http://docs.python.org/2/library/csv.html查看文檔。

編寫CSV文件的最簡單方法如下:

import csv

records = [[1951, 'Superman and the Mole Men', 'DC Comics', 'Lee Sholem'],
           [1966, 'Batman', 'DC Comics', 'Leslie H. Martinson'],
           [2002, 'Spider-Man', 'Marvel Comics', 'Sam Raimi'],
           [2008, 'Iron Man', 'Marvel Comics', 'Jon Favreau']]

with open('heros.csv', 'wb') as fp:
    writer = csv.writer(fp)
    writer.writerows(records)

結果是一個經典的CSV文件:

1951,Superman and the Mole Men,DC Comics,Lee Sholem
1966,Batman,DC Comics,Leslie H. Martinson
2002,Spider-Man,Marvel Comics,Sam Raimi
2008,Iron Man,Marvel Comics,Jon Favreau

當然,您可以添加標題:

with open('heros.csv', 'wb') as fp:
    writer = csv.writer(fp)
    writer.writerows([['Year', 'Film', 'Publisher', 'Director']])
    writer.writerows(records)

注意:頁眉是列表的列表(請查看雙括號)

結果是以下CSV文件:

Year,Film,Publisher,Director
1951,Superman and the Mole Men,DC Comics,Lee Sholem
1966,Batman,DC Comics,Leslie H. Martinson
2002,Spider-Man,Marvel Comics,Sam Raimi
2008,Iron Man,Marvel Comics,Jon Favreau

讀取HTML表格

首先,使用with語句以安全方式打開文件。

例如,要讀取文本文件,請執行以下步驟:

with open('sample.txt', 'r') as fp:
    content = fp.read()

這樣,如果在讀取期間發生錯誤,該文件將在引發異常之前在with語句的末尾自動關閉。 什么都沒有打開!

要使用BeautifulSoup (我不知道)讀取HTML表,可以執行以下操作:

with open("/company/a/searches/a") as html_file:
    soup = BeautifulSoup(html_file)
    rows = soup.findAll("table", {"id": "cos"})
    records = []
    for tr in rows:
        record = []
        cols = tr.findAll('td')
        for td in cols:
            record.append(td.contents[0])
        records.append(record)

records列表將包含整個表。 然后,您可以將其寫入CSV文件。

處理UNICODE值

HTML不包含ASCII字符串,但包含UNICODE字符串,我想td.contents[0]將返回一個unicode實例。

但是, csv模塊不直接支持讀寫Unicode。 因此,您將需要在CSV序列化期間使用UTF-8編碼編寫unicode字符串。 我建議您在示例中查看unicode_csv_reader()函數: http : unicode_csv_reader()

rows = soup.findAll("table",{"id":"cos"})[0].findAll('tr')
records = []
for tr in rows:
  cols = tr.findAll('td')
  record = ''
  for td in cols:
    if record != '': record = record + ', '
    record = record + td.contents[0]
  records.append(record + "\n")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM