写入csv文件python的第二列

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了写入csv文件python的第二列相关的知识,希望对你有一定的参考价值。

我有一个Python程序,可以从CSV文件(只有一列)中读取餐厅名称,从而获得餐厅的Google评级。名称在单列(第一列)中。它获取每个餐厅的评分并将其附加到列表中。现在,我需要做第二列,并将该列表传递到第二列。这是我的CSV文件(它没有标题,即列名)

Barrafina london
palomar london
fateema london
five guys london
10 greek street london
edition hotel london

这是代码:

import requests
from bs4 import BeautifulSoup
import csv


def main():
    global rate
    ratings = []
    res = []
    with open('CSV restaurants example.csv', newline='', encoding='utf-8') as f:
        reader = csv.reader(f)

        for row1 in reader:
            for row in row1:
                res.append(row)
    for restaurant in res:
        try:
            re = requests.get('https://www.google.com/search?q=' + restaurant)
        except requests.exceptions.ChunkedEncodingError:
            re = requests.get('https://www.google.com/search?q=' + restaurant)

        soup = BeautifulSoup(re.content, 'html.parser')

        rating = soup.select_one('.oqSTJd')
        try:
            rate = rating.text
            ratings.append(rate)
        except AttributeError:
            print("google search is asking for captcha, use a proxy or change your wifi network")
            exit()

        print('
The rating for ' + restaurant + ' is ' + str(rate) + ' out of 5 ' + '
')


if __name__ == '__main__':
    main()

关于如何将该列表附加到第二列的任何建议?

答案

尝试一下,它将创建一个熊猫的对象,并在其第二列中将其转换为csv:

import requests
import pandas as pd
from bs4 import BeautifulSoup
import csv


def main():
    global rate
    ratings = []
    res = []
    with open('CSV restaurants example.csv', newline='', encoding='utf-8') as f:
        reader = csv.reader(f)

        for row1 in reader:
            for row in row1:
                res.append(row)
    for restaurant in res:
        try:
            re = requests.get('https://www.google.com/search?q=' + restaurant)
        except requests.exceptions.ChunkedEncodingError:
            re = requests.get('https://www.google.com/search?q=' + restaurant)

        soup = BeautifulSoup(re.content, 'html.parser')

        rating = soup.select_one('.oqSTJd')
        try:
            rate = rating.text
            ratings.append(rate)
        except AttributeError:
            print("google search is asking for captcha, use a proxy or change your wifi network")
            exit()

        print('
The rating for ' + restaurant + ' is ' + str(rate) + ' out of 5 ' + '
')
    df2 = pd.read_csv('CSV restaurants example.csv', header=None, names=['Restaurants']) 
    df2['ratings'] = ratings
    print(df2)
    print(df2.to_csv())

if __name__ == '__main__':
    main()

以上是关于写入csv文件python的第二列的主要内容,如果未能解决你的问题,请参考以下文章

将python字典写入CSV列:第一列的键,第二列的值

Python - 需要帮助将字典字典写入 CSV 文件

python 如何将列表写入文件

如何将两列csv转换为第二列的向量?

从 csv 文件创建字典?

当第二列和第三列与数字模式匹配时打印整行