我一直在努力解决这个简单的问题,所以我想我会寻求帮助.我正在尝试将国家医学图书馆ftp站点的期刊文章列表读入Python 3.3.2(在Windows 7上).期刊文章位于.csv文件中.
我试过以下代码:
import csv
import urllib.request
url = "ftp://ftp.ncbi.nlm.nih.gov/pub/pmc/file_list.csv"
ftpstream = urllib.request.urlopen(url)
csvfile = csv.reader(ftpstream)
data = [row for row in csvfile]
它会导致以下错误:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
data = [row for row in csvfile]
File "<pyshell#4>", line 1, in <listcomp>
data = [row for row in csvfile]
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
我认为我应该使用字符串而不是字节?任何有关简单问题的帮助,以及对出现问题的解释都将非常感激.
寻找一种使用Python urllib2或任何其他Python库获取HTTP响应的字符集/编码信息的简单方法.
>>> url = 'http://some.url.value'
>>> request = urllib2.Request(url)
>>> conn = urllib2.urlopen(request)
>>> response_encoding = ?
我知道它有时出现在'Content-Type'标题中,但该标题有其他信息,并且它嵌入在我需要解析的字符串中.例如,Google返回的Content-Type标头是
>>> conn.headers.getheader('content-type')
'text/html; charset=utf-8'
我可以使用它,但我不确定格式的一致性.我很确定charset可能完全丢失,所以我必须处理这个边缘情况.某种类型的字符串拆分操作使得"utf-8"从中看出来似乎是做错这种事情的错误方法.
>>> content_type_header = conn.headers.getheader('content-type')
>>> if '=' in content_type_header:
>>>  charset = content_type_header.split('=')[1]
这种代码感觉就像做了太多的工作.我也不确定它是否适用于所有情况.有没有人有更好的方法来做到这一点?
我一直在尝试更新一个名为libpynexmo的小型Python库来使用Python 3.
我一直坚持这个功能:
def send_request_json(self, request):
    url = request
    req =  urllib.request.Request(url=url)
    req.add_header('Accept', 'application/json')
    try:
        return json.load(urllib.request.urlopen(req))
    except ValueError:
        return False
当它到达时,json回应:
TypeError: the JSON object must be str, not 'bytes'
我在几个地方读到,json.load你应该传递HTTPResponse带有.read()附件的对象(在这种情况下是一个对象),但它不适用于HTTPResponse对象.
我不知道下一步该怎么做,但由于我的整个1500行脚本刚刚转换为Python 3,我不想回到2.7.
[根据/sf/answers/3245896181/,标题应参考集成测试而不是单元测试]
假设我想测试以下Flask API(从这里开始):
import flask
import flask_restful
app = flask.Flask(__name__)
api = flask_restful.Api(app)
class HelloWorld(flask_restful.Resource):
    def get(self):
        return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
if __name__ == "__main__":
    app.run(debug=True)
将此保存flaskapi.py并运行后,在同一目录中运行脚本test_flaskapi.py:
import unittest
import flaskapi
import requests
class TestFlaskApiUsingRequests(unittest.TestCase):
    def test_hello_world(self):
        response = requests.get('http://localhost:5000')
        self.assertEqual(response.json(), {'hello': 'world'})
class TestFlaskApi(unittest.TestCase):
    def setUp(self):
        self.app = flaskapi.app.test_client()
    def test_hello_world(self):
        response = self.app.get('/')
if __name__ == "__main__":
    unittest.main()
两个测试都通过了,但对于第二个测试(在TestFlaskApi类中定义),我还没有弄清楚如何断言JSON响应是否符合预期(即{'hello': 'world'}).这是因为它是一个实例flask.wrappers.Response(可能基本上是一个Werkzeug响应对象(参见http://werkzeug.pocoo.org/docs/0.11/wrappers/)),但我找不到相应的Response …
$.ajax({
    type: "POST",
    url: "SomePage.aspx/GetSomeObjects",
    contentType: "application/json; charset=utf-8",
    ...
});
它有时用作示例,或者软件可以在没有显式字符集的情况下中断.
应用程序/ json媒体类型的rfc 4627表示它不接受第6节中的任何参数:
The MIME media type for JSON text is application/json.
Type name: application
Subtype name: json
Required parameters: n/a
Optional parameters: n/a
可以解释为charset不应该与application/json一起使用.
和第3节表明,这是没有必要指定字符集:
JSON text SHALL be encoded in Unicode.  The default encoding is
UTF-8.
Since the first two characters of a JSON text will always be ASCII
characters [RFC0020], it is possible to determine whether …我在使用服务 api 生成 JSON 响应的 Web 应用程序中使用烧瓶。该函数的以下部分工作正常并返回 JSON 文本输出:
def get_weather(query = 'london'):
    api_url = "http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=XXXXX****2a6eaf86760c"
    query = urllib.request.quote(query)
    url = api_url.format(query)
    response = urllib.request.urlopen(url)
    data = response.read()    
    return data
返回的输出是:
{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"cmc stations","main":{"temp":12.95,"pressure":1030,"humidity":68,"temp_min":12.95,"temp_max":12.95,"sea_level":1039.93,"grnd_level":1030},"wind":{"speed":5.11,"deg":279.006},"clouds":{"all":76},"dt":1462290955,"sys":{"message":0.0048,"country":"GB","sunrise":1462249610,"sunset":1462303729},"id":2643743,"name":"London","cod":200}
这意味着这data是一个字符串,不是吗?
但是,评论return data然后添加以下两行:
jsonData = json.loads(data)
return jsonData
产生以下错误:
类型错误:JSON 对象必须是 str,而不是 'bytes'
怎么了?data,JSON 对象,以前作为字符串返回!我需要知道错误在哪里?
我正在尝试开发一个应用程序来检索股票价格(以 JSON 格式),然后对其进行一些分析。我的问题是将 JSON 响应放入我可以工作的 pandas DataFrame 中。这是我的代码:
'''
References
http://stackoverflow.com/questions/6862770/python-3-let-json-object-  accept-bytes-or-let-urlopen-output-strings
'''
import json
import pandas as pd
from urllib.request import urlopen
#set API call
url = "https://www.quandl.com/api/v3/datasets/WIKI/AAPL.json?start_date=2017-01-01&end_date=2017-01-31"
#make call and receive response
response = urlopen(url).read().decode('utf8')
dataresponse = json.loads(response)
#check incoming
#print(dataresponse)
df = pd.read_json(dataresponse)
print(df)
应用程序出现df = pd.read_json...错误TypeError: Expected String or Unicode。
所以我认为这是第一个障碍。
第二是到达我需要去的地方。JSON 响应仅包含两个我感兴趣的数组,column_names和data。如何仅提取这两个并将其放入 pandas DataFrame 中?
json ×4
python ×4
python-3.x ×4
flask ×2
csv ×1
dataframe ×1
http ×1
httprequest ×1
nexmo ×1
pandas ×1
python-3.4 ×1
url ×1
urllib2 ×1
werkzeug ×1