[英]How should one go about collecting data from a .CSV file using Python?
I am attempting to use the Yahoo! 我正在尝试使用Yahoo! Finance API to gather current stock quotes using Python, a language I am particularly new to. Finance API使用Python(我特别陌生的一种语言)来收集当前的股票报价。 The Yahoo! 雅虎! Finance API appears to offer their data in the form of a .CSV file that can be downloaded. Finance API似乎以可以下载的.CSV文件的形式提供其数据。
I am wondering what the best way to use this data is? 我想知道使用此数据的最佳方法是什么? Is it inefficient to download the file and then read it; 下载文件然后阅读它效率低下吗? is there a method to convert it to a JSON or XML file that I can parse using something like urllib? 有没有一种方法可以将其转换为我可以使用类似urllib解析的JSON或XML文件?
The .CSV I am getting is being generated on the following page, in this case the quote for Microsoft (MSFT): 我正在获取的.CSV会在下一页生成,在这种情况下,Microsoft(MSFT)的报价是:
http://finance.yahoo.com/d/quotes.csv?s=MSFT&f=snl1 http://finance.yahoo.com/d/quotes.csv?s=MSFT&f=snl1
Many thanks in advance. 提前谢谢了。
Python has a built in csv
module. Python具有内置的csv
模块。
http://docs.python.org/library/csv.html http://docs.python.org/library/csv.html
To answer your downloading question: 要回答您的下载问题:
file = r"http://finance.yahoo.com/d/quotes.csv?s=MSFT&f=snl1"
import urllib
text = urllib.urlopen(file).read()
>>> print text
... "MSFT","Microsoft Corpora",29.51
Based on csv
module and DictReader
, it will be more easy to parse data after urlopen, I reuse the code above from @kreativitea 基于csv
模块和DictReader
,在urlopen之后解析数据会更加容易,我重用了@kreativitea中的代码
import csv
import urllib
file = r"http://finance.yahoo.com/d/quotes.csv?s=MSFT&f=snl1"
quotefile = urllib.urlopen(file)
fieldheaders = ["abbr","name","index"]
reader = csv.DictReader(quotefile,fieldnames=fieldheaders)
for row in reader:
print row
the result is 结果是
$ quote.py
{'index': '29.51', 'abbr': 'MSFT', 'name': 'Microsoft Corpora'}
the row
in for loop is the hash table, which is easy to deal with for循环中的row
是哈希表,很容易处理
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.