Python将数据更改为顺序

时间:2010-09-03 17:11:25

标签: python url

我从此网址中提取的“idata”需要转换为序列,如何将其转换为序列

import urllib, csv

URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1vt1&e=.csv"
symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN')
#symbols = ('GGP',)

def fetch_quote(symbols):
    url = URL % '+'.join(symbols)
    fp = urllib.urlopen(url)
    try:
        data = fp.read()
    finally:
        fp.close()
    return data # <======== Return

idata = fetch_quote(symbols)
print idata

Python URL download

2 个答案:

答案 0 :(得分:1)

我会根据您以CSV格式下载数据的网址进行猜测。因此,您可能希望使用CSV reader对其进行解析。

答案 1 :(得分:1)

“序列”是什么意思?您可以将其转换为字典,如下所示。只需在生成idata后放置此代码。

stocks = {}
for line in idata.split("\r\n"):
    if line == '':
        continue

    stock, price, volume, stime = line.split(',')
    stock = stock[1:-1]
    price = float(price)
    volume = int(volume)
    stime = stime[1:-1]

    stocks[stock] = (price, volume, stime)

如果您想要更强大,可以使用csv模块(在代码顶部添加import csv)然后使用

reader = csv.reader(idata.split("\r\n"))

stocks = {}
for line in reader:
    if line == '':
        continue

    stock, price, volume, stime = line
    price = float(price)
    volume = int(volume)

    stocks[stock] = (price, volume, stime)

要插入数据库,以下内容可能有效

reader = csv.reader(idata.split("\r\n"))

stocks = []
for line in reader:
    if line == '':
        continue

    stock, price, volume, stime = line
    price = float(price)
    volume = int(volume)

    stocks.append((stock, price, volume, stime))

csr.executemany('INSERT INTO test.prices VALUES (?,?,?,?)', stocks)

这当然假设您的列与数组元素的顺序相同。