如何创建一个循环,以便通过python将所有查询输入到一个csv中?

时间:2018-06-27 14:12:59

标签: python pandas api

我创建了一个函数,可以在点击API后获取价格,价格等:

def is_priced(business_id):
    try:
        priced_ind = get_business(API_KEY, business_id)
        priced_ind1 = priced_ind['price']
    except:
        priced_ind1 = 'None'
    return priced_ind1

priced_ind = is_priced(b_id)
print(priced_ind)

与评级类似

def is_rated(business_id):

    try:
        rated_ind = get_business(API_KEY, business_id)

        rated_ind1 = rated_ind['rating']
    except:
        rated_ind1 = 'None'
    return rated_ind1

但是,我希望我的函数在CSV文件中循环显示我的公司名称,并捕获所有这些数据,并使用公司名称旁边的这两个参数将其导出到新的csv文件中。

CSV文件包含有关商家名称的信息以及其地址,城市,州,邮政编码和国家/地区

例如:

Name        address             city            state zip    country
XYZ(The)    5* WE 223899th St.  New York        NY    19921       US

我的输出:

Querying https://api.xyz.com/v3/businesses/matches ...
True
Querying https://api.xyz.com/v3/businesses/matches ...
4.0
Querying https://api.xyz.com/v3/businesses/matches ...
$$
Querying https://api.xyz.com/v3/businesses/matches ...
Querying https://api.xyz.com/v3/businesses/matches ...

真正的问题是我的输出仅在csv中返回业务ID。并且您看到的评分等仅在控制台中返回。如何设置一个循环,使所有企业将我想要的信息返回到单个CSV中?

3 个答案:

答案 0 :(得分:0)

csv模块可用于此类事情,例如

import csv

with open('f.csv', 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='"')
    with open('tmp.csv', 'w') as output:
        writer = csv.writer(output)
        for row in reader:
            business_id = row[0]
            row.append(get_price_index(business_id))
            row.append(get_rate_index(business_id))
            writer.writerow(row)

答案 1 :(得分:0)

您可以从CSV文件中读取商户名称,使用for循环对其进行迭代,点击API并存储结果,然后写入新的CSV文件。

import csv

data = []

with open('businesses.csv') as fp:
    # skip header line
    header = next(fp)
    reader = csv.reader(fp)
    for row in reader:
        b_name = reader[0]
        # not sure how you get the business ID:
        b_id = get_business_id(b_name)
        p = is_priced(b_id)
        r = is_rated(b_id)
        out.append((b_name, p, r))

# write out the results
with open('business_data.csv', 'w') as fp:
    writer = csv.writer(fp)
    writer.writerow(['name', 'price', 'rating'])
    for row in data:
        writer.writerow(row)

答案 2 :(得分:0)

您可以使用pandas轻松完成此操作:

import pandas as pd
csv = pd.read_csv('your_csv.csv', usecols=['business_name']) # since you only need the name
# you'll receive business_name in your functions
csv = csv.apply(is_priced, axis=1) 
csv = csv.apply(is_rated, axis=1)
csv.to_csv('result.csv', index=False)

您在功能中所要做的就是:

def is_priced(row):
    business_name = row['business_name']
    business_id = ??
    ...