Python CSV解析未返回正确的行 [英] Python CSV parsing not returning proper rows

查看:70
本文介绍了Python CSV解析未返回正确的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,并且CSV解析器有问题.这是代码:

I'm new to python and having issues with the CSV parser. Here is the code:

import urllib2
import csv


u = urllib2.urlopen(r'http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=nab')
data = u.read()

reader = csv.reader(data)

for row in reader:
    print row

Yahoo返回此原始csv:

Yahoo returns this raw csv:

"Apple Inc.",482.09,482.00
"Google Inc.",877.20,876.94
"Microsoft Corpora",33.34,33.33

我想对此进行解析,并创建一个具有3个字段的简单JSON对象:股票代码,出价,报价

I want to parse this and create a simple JSON object with 3 fields: Ticker, Bid, Offer

但是数据像这样从csv.reader()输入:

But the data comes in from that csv.reader() like so:

['Apple Inc.']
['', '']
['4']
['8']
['2']
['.']
['5']
['5']
['', '']
['4']
['8']
['2']
['.']
['4']
['8']
[]
[]
['Google Inc.']
['', '']
['8']
['7']
['6']
['.']
['2']
['4']
['', '']
['8']
['7']
['6']
['.']
['1']
['0']
[]
[]
['Microsoft Corpora']
['', '']
['3']
['3']
['.']
['2']
['9']
['', '']
['3']
['3']
['.']
['2']
['8']
[]
[]

似乎打破了每个数字的行.关于我在这里做错什么的任何想法吗?

It seems to be breaking the rows on each number. Any ideas as to what I'm doing wrong here?

推荐答案

只需将 u 解析为阅读器即可:

Just parse u directly into the reader:

import urllib2
import csv

u = urllib2.urlopen(r'http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=nab')

reader = csv.reader(u)

for row in reader:
    print row

问题是 csv.reader 接受可迭代的行.当您传递一个字符串时,它会认为每个字符都是一行.实际上,之所以不仅仅提供单个字符的元素,是因为引号引起来.

The problem is that csv.reader accepts an iterable of lines. When you pass it a string, it thinks each character is a line. In fact, the reason it doesn't just give single-character elements is due the the quotation marks.

u 已经是行的迭代,因此只需传递即可.

u is already an iterable of lines, so it's fine to just pass in.

这篇关于Python CSV解析未返回正确的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆