2016-10-27 63 views
-3

我在Python2.7中運行了一個非常簡單的BeautifulSoup,我需要在Python3中運行它。輸出是一個csv文件。在Python2中,我可以直接將它導入到Excel中,但是在Python3中,字段會以b'text的形式出現並加載到該窗體中的單元格中。我從來沒有碰過Python3,所以很感激一些指導。Python3 b'text'而不是u'text'

相關代碼:

for d in data: 
    row = [] 
    name = d.find('a') 
    addr = d.find('span', attrs = {'class' : 'center_address'}) 
    city = d.find('span', attrs = {'class' : 'center_city'}) 
    state = d.find('span', attrs = {'class' : 'center_state_abbr'}) 
    zip = d.find('span', attrs = {'class' : 'center_zip'}) 

    row.append(str(name.text)) 
    row.append(addr.text) 
    row.append(city.text) 
    row.append(state.text) 
    row.append(zip.text) 

    list_of_rows.append(row) 

with open("./output.csv", "w") as outfile: 
    writer = csv.writer(outfile) 
    writer.writerow(["Name","Address", "City","State","Zip"]) 
    writer.writerows([s.strip().encode("utf-8") for s in row ]for row in list_of_rows) 
outfile.close() 

回答

1

已打開在文本模式輸出文件,這意味着你要發送的Unicode文本字符串,但你沒有 - 你正在服用的Unicode字符串和將它們轉換爲編碼的字節數據。

取出編碼步驟讓你的代碼讀取

with open("./output.csv", "w") as outfile: 
    writer = csv.writer(outfile) 
    writer.writerow(["Name","Address", "City","State","Zip"]) 
    writer.writerows(([s.strip() for s in row ] 
           for row in list_of_rows)) 

的Python 3下

將工作
相關問題