简体   繁体   English

Python 3.5 | 拆分列表并导出到Excel或CSV

[英]Python 3.5 | split List and export to Excel or CSV

I scrape a website with Python 3.5 (BeautifulSoup) and the result is a list. 我用Python 3.5(BeautifulSoup)抓取了一个网站,结果是一个列表。 The values are stored in a variable called "project_titles". 这些值存储在一个名为“ project_titles”的变量中。

The values look like: 值如下所示:

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']

I want to split the values at the comma and export this to an Excel file or CSV. 我想在逗号处分割值并将其导出到Excel文件或CSV。

I need the values in an Excel like: 我需要像这样的Excel中的值:

  • Cell A1: I'm Back. 单元格A1:我回来了。 Raspberry Pi unique Case for your Analog Cameras Raspberry Pi适用于模拟相机的独特保护套
  • Cell B1: CitizenSpring - App to crowdsource & map safe drinking water 单元格B1:CitizenSpring-用于众包和映射安全饮用水的应用
  • Cell C1: Shoka Bell: The Ultimate City Cycling Tool 单元格C1:Shuka Bell:终极城市骑行工具

Since you already have a list of strings conforming to the columns required in your CSV file you can simply write the list out using the csv module: 由于您已经有了符合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)

After running this code the output CSV file would contain: 运行此代码后,输出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

which you can import into Excel. 您可以将其导入Excel。

Since project_titles is already a list containing the strings you want, it's easy to use pandas (can be installed together with one of the scientific Python distributions, see scipy.org ) with the following short code: 由于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()

You can try a very simple code 您可以尝试一个非常简单的代码

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM