【问题标题】:Python 3.5 | split List and export to Excel or CSVPython 3.5 |拆分列表并导出到 Excel 或 CSV
【发布时间】:2016-12-15 13:31:25
【问题描述】:

我用 Python 3.5 (BeautifulSoup) 抓取了一个网站,结果是一个列表。这些值存储在名为“project_titles”的变量中。

值看起来像:

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:我回来了。 Raspberry Pi 独特的模拟相机保护套
  • Cell B1:CitizenSpring - 用于众包和绘制安全饮用水地图的应用
  • Cell C1:Shoka Bell:终极城市骑行工具

【问题讨论】:

    标签: python excel python-3.x csv beautifulsoup


    【解决方案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()
    

    【讨论】:

      【解决方案2】:

      你可以试试很简单的代码

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

      【讨论】:

        【解决方案3】:

        由于您已经拥有符合 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 文件将包含:

        我回来了。 Raspberry Pi 独特的模拟相机保护壳,CitizenSpring - 众包和映射安全饮用水的应用程序,Shoka Bell:终极城市骑行工具

        您可以将其导入 Excel。

        【讨论】:

        • 嗨......它的工作原理!您可以更改代码,将值插入到列中。像A1、A2、A3等等。很抱歉
        • 当您导入 CSV 文件时,值将自动进入名为 A1、B1、C1 等的单元格中。如果您想专门为文件添加标题,只需使用 @ 将它们写为第一行987654324@.
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-20
        • 2021-07-04
        相关资源
        最近更新 更多