我开始使用请求库了。

import requests

ticker='ibm'
startMonth='1'
startDate='1'
startYear='2013'

nowMonth='3'
nowDate='1'
nowYear='2014'

test='http://ichart.finance.yahoo.com/table.csv?s=' + ticker + '&a=' + startMonth + "&b=" + startDate + "&c=" + startYear + "&d=" + nowMonth + "e=" + nowDate + "&f=" + nowYear + "&g=d"

r=requests.get(test)
data=r.text

我如何获取文本并将其转换为7个单独的列表?我不需要第一排
Date,Open,High,Low,Close,Volume,Adj Close
2014-03-28,189.94,192.62,189.11,190.45,5193700,190.45
2014-03-27,191.91,192.67,189.32,189.83,6767700,189.83
2014-03-26,194.98,195.63,191.96,192.62,6851700,192.62

我希望它看起来像这样
Date = [2014-03-28,2014-03-27,2014-03-26]
Open = [189.94,191.91,194.98]
High = ...
...

最佳答案

您可以使用zip(*data)来转置序列。
例子:

input = """Date,Open,High,Low,Close,Volume,Adj Close
2014-03-28,189.94,192.62,189.11,190.45,5193700,190.45
2014-03-27,191.91,192.67,189.32,189.83,6767700,189.83
2014-03-26,194.98,195.63,191.96,192.62,6851700,192.62"""

# split by newline, then each element by ','
data = [v.split(',') for v in input.rstrip().split('\n')]

# transpose the data and wrap it in a nice dict
result = {e[0]: e[1:] for e in zip(*data)}

# just for a pretty output
import pprint
pprint.pprint(result)

输出:
{'Adj Close': ('190.45', '189.83', '192.62'),
 'Close': ('190.45', '189.83', '192.62'),
 'Date': ('2014-03-28', '2014-03-27', '2014-03-26'),
 'High': ('192.62', '192.67', '195.63'),
 'Low': ('189.11', '189.32', '191.96'),
 'Open': ('189.94', '191.91', '194.98'),
 'Volume': ('5193700', '6767700', '6851700')}

关于python - 文字串成 list ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22746233/

10-16 07:00
查看更多