2016-08-09 107 views
0

我使用Python 3.5(BeautifulSoup)抓取網站,結果是一個列表。這些值存儲在一個名爲「project_titles」的變量中。Python 3.5 |分割列表並導出爲Excel或CSV

值樣子:

project_titles = ['I'm Back. Raspberry Pi unique Case for your Analog Cameras', 'CitizenSpring - App to crowdsource & map safe drinking water', 'Shoka Bell: The Ultimate City Cycling Tool'] 

我想要的值在逗號分開,這導出到Excel文件或CSV。

我所需要的值在Excel這樣的:

  • 單元格A1:我回來了。樹莓派你的模擬攝像機
  • 小區B1獨特的案例:CitizenSpring - 應用到衆包&地圖安全飲用水
  • 格C1:舒卡貝爾:終極城市自行車工具

回答

2

既然你已經有一個列表符合您的CSV文件,你可以簡單地寫了出來列表使用csv模塊所需的列字符串:

import csv 

project_titles = ["I'm Back. Raspberry Pi unique Case for your Analog Cameras", 'CitizenSpring - App to crowdsource & map safe drinking water', 'Shoka Bell: The Ultimate City Cycling Tool'] 

with open('projects.csv', 'w') as f: 
    csv.writer(f).writerow(project_titles) 

運行此代碼後輸出CSV文件將包含:

 
I'm Back. Raspberry Pi unique Case for your Analog Cameras,CitizenSpring - App to crowdsource & map safe drinking water,Shoka Bell: The Ultimate City Cycling Tool 

您可以導入到Excel中。

+0

嗨...它的工作原理!你可以改變代碼,這些值將被插入到列中。像A1,A2,A3等。對不起, –

+0

導入CSV文件時,這些值將自動進入名爲A1,B1,C1等的單元格中。如果要專門爲文件添加標題,只需將它們作爲第一行使用'writerow(['' A1','B1','C1'])'。 – mhawke

1

由於project_titles已經包含所需的字符串列表,可以很容易地使用pandas(可以用科學的Python發行之一一起安裝,見scipy.org)與下面的短代碼:

import pandas as pd 

project_titles = ["I'm Back. Raspberry Pi unique Case for your Analog Cameras", 
       'CitizenSpring - App to crowdsource & map safe drinking water', 
       'Shoka Bell: The Ultimate City Cycling Tool'] 


d = pd.DataFrame(project_titles) 
writer = pd.ExcelWriter('data.xlsx') 
d.to_excel(writer, 'my_data', index=False, header=False) 
writer.save() 
0

你可以嘗試一個非常簡單的代碼

project_titles = ["I'm Back. Raspberry Pi unique Case for your Analog Cameras", 'CitizenSpring - App to crowdsource & map safe drinking water', 'Shoka Bell: The Ultimate City Cycling Tool'] 

with open('data.csv',"w") as fo: 
    fo.writelines(",".join(project_titles))