gpt4 book ai didi

python - python 写入 csv 文件的第二列

转载 作者:行者123 更新时间:2023-12-01 06:49:19 25 4
gpt4 key购买 nike

我有一个 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('\nThe rating for ' + restaurant + ' is ' + str(rate) + ' out of 5 ' + '\n')


if __name__ == '__main__':
main()

关于如何将该列表附加到第二列有什么建议吗?

最佳答案

只需创建一个 csv.writer 来补充您的 csv.reader。如果您想将输出保存为新文件,我建议您永远不要覆盖原始数据,即使您只是向其中添加数据。

我想说的是,您可能需要小心分隔符,因为位置和餐厅字段似乎已合并,对我来说,这看起来就像格式不正确的 csv 中的两列。

在这里您可以在同一个 for 循环中解决它:

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 infd, \
open('restaurants_with_ratings.csv') as outfd:
reader = csv.reader(infd)

# create a csv writer, these are defaults, but I'm showing that
# you can choose formatting
writer = csv.writer(outfd, delimiter=',', quotechar='"')

# if there's only one column, the comma works here.
for restaurant, in reader:
# res.append(row)

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
writer.writerow([restauant, rate]) # add a column
# ratings.append(rate)
except AttributeError:
print("google search is asking for captcha, use a proxy or change your wifi network")
exit()

print('\nThe rating for ' + restaurant + ' is ' + str(rate) + ' out of 5 ' + '\n')


if __name__ == '__main__':
main()

关于python - python 写入 csv 文件的第二列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59095546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com