通过API获取的CSV文件无法正确打印到单独的行中

2024-09-30 01:27:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还很陌生,我正试图通过观看视频/阅读教程来尽可能多地学习

我正在关注this video如何从Quandl获取数据。我知道python已经有了一个特定的模块,但是我想在必要时从网站上学习如何使用它。我的问题是,当我尝试在9:50左右模拟代码并打印结果时,python不会分割CSV file中的行。我知道他用的是Python2.x,而我用的是3.4

以下是我使用的代码:

import urllib
from urllib.request import urlopen

def grabQuandl(ticker):
    endLink = 'sort_order=desc'#without authtoken

    try:
        salesRev = urllib.request.urlopen('https://www.quandl.com/api/v1/datasets/SEC/'+ticker+'_SALESREVENUENET_Q.csv?&'+endLink).read()

        print (salesRev)   

    except Exception as e:
        print ('failed the main quandl loop for reason of', str(e))

grabQuandl('AAPL')

这就是印刷的内容:

b'Date,Value\n2009-06-27,8337000000.0\n2009-12-26,15683000000.0\n2010-03-27,13499000000.0\n2010-06-26,15700000000.0\n2010-09-25,20343000000.0\n2010-12-25,26741000000.0\n2011-03-26,24667000000.0\n2011-06-25,28571000000.0\n2011-09-24,28270000000.0\n2011-12-31,46333000000.0\n2012-03-31,39186000000.0\n2012-06-30,35023000000.0\n2012-09-29,35966000000.0\n2012-12-29,54512000000.0\n2013-03-30,43603000000.0\n2013-06-29,35323000000.0\n2013-09-28,37472000000.0\n2013-12-28,57594000000.0\n2014-03-29,45646000000.0\n2014-06-28,37432000000.0\n2014-09-27,42123000000.0\n2014-12-27,74599000000.0\n2015-03-28,58010000000.0\n'

我知道\n是一种分线器,但它不像视频中那样工作。我在google中搜索过可能的解决方案,例如使用read().split()执行for循环,但充其量只是删除\n。我不能像视频中那样把输出放到表中。我做错什么了


Tags: 代码import视频requesturlliburlopentickern2011
1条回答
网友
1楼 · 发布于 2024-09-30 01:27:46

.read()返回一个字节字符串,当您直接打印它时,您将得到您得到的结果。您可以注意到在引号之前的开始处的b,它表示字节字符串

您应该在打印之前(或直接使用.read()对得到的字符串进行解码。举个例子-

import urllib
from urllib.request import urlopen

def grabQuandl(ticker):
    endLink = 'sort_order=desc'#without authtoken

    try:
        salesRev = urllib.request.urlopen('https://www.quandl.com/api/v1/datasets/SEC/'+ticker+'_SALESREVENUENET_Q.csv?&'+endLink).read().decode('utf-8')

        print (salesRev)   

    except Exception as e:
        print ('failed the main quandl loop for reason of', str(e))

grabQuandl('AAPL')

上面使用utf-8编码对返回的数据进行解码,您可以使用您想要的任何编码(数据的任何编码)


显示打印行为的示例-

>>> s = b'asd\nbcd\n'
>>> print(s)
b'asd\nbcd\n'
>>> print(s.decode('utf-8'))
asd
bcd

>>> type(s)
<class 'bytes'>

相关问题 更多 >

    热门问题