【问题标题】:Python - Exporting PyGoogleNews output to CSVPython - 将 PyGoogleNews 输出导出到 CSV
【发布时间】:2022-01-21 06:05:31
【问题描述】:

我是 Python 新手,我正在尝试使用 PyGoogleNews 库从 Google News Feed 中提取标题。我正在使用谷歌 Colab。 PyGoogleNews 代码对我来说运行得很好,我对此很满意。代码正在创建 csv,但我无法使用抓取的标题结果填充 csv。我想将抓取的标题输出导出到 csv 文件中,因为我将执行情绪分析并下载/提取它以对其进行进一步分析。我会非常感谢任何帮助,因为这已经困扰了我好几天了,我相信这是非常明显的事情!提前谢谢你。

!pip install pygooglenews --upgrade 
import pandas as pd
import csv
from pygooglenews import GoogleNews

gn = GoogleNews (lang = 'en', country = 'UK') 

Xmassearch = gn.search('intitle:Christmas', helper = True, from_ = '2019-12-01', to_= '2019-12-31')

print(Xmassearch['feed'].title)

for item in Xmassearch ['entries']:
  print(item['title'])

file = open("Christmassearch.csv", "w")
writer = csv.writer(file)

writer.writerow(["Xmassearch"])

file.close()

【问题讨论】:

    标签: python csv export pygooglenews


    【解决方案1】:

    我没有 GoogleNews,也找不到任何使用关键字 entries 的文档,所以我无法确切说明它应该如何工作,所以...

    如果迭代 Xmassearch['entries'] 适合您,则将该迭代向下移动到您打开 CSV 并开始编写的位置。

    我还重新编写/构建了您的文件处理以使用 Python 的 with 复合语句,因此您不必管理文件的关闭:

    with open('Christmassearch.csv', 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['Xmassearch'])  # I presume you meant this to be your header
        
        # Use your loop from before...
        for item in Xmassearch ['entries']:
            # And write each item
            writer.writerow([item['title']])
    

    【讨论】:

      猜你喜欢
      • 2015-01-17
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 2015-02-01
      • 2014-06-11
      • 1970-01-01
      • 2016-11-10
      • 2019-11-09
      相关资源
      最近更新 更多