繁体   English   中英

TypeError:需要类似字节的对象,而不是'str'-python

[英]TypeError: a bytes-like object is required, not 'str' -python

我使用的是python 3,第42行的代码导致了问题

第42行,打印('检索',len(数据),'字符',数据[:20] .replace('\\ n',''))TypeError:需要类似字节的对象,而不是'str'

在我的程序行-42中

 print ('Retrieved',len(data),'characters',data[:20].replace('\n',' '))

我将非常感谢你的帮助。

以下是完整的感冒:

import urllib
import urllib.request
import sqlite3
import json
import time
import ssl

# If you are in China use this URL:
# serviceurl = "http://maps.google.cn/maps/api/geocode/json?"
serviceurl = "http://maps.googleapis.com/maps/api/geocode/json?"

# Deal with SSL certificate anomalies Python > 2.7
# scontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
scontext = None

conn = sqlite3.connect('geodata.sqlite')
cur = conn.cursor()

cur.execute('''
CREATE TABLE IF NOT EXISTS Locations (address TEXT, geodata TEXT)''')

fh = open("where.data", encoding="utf-8")
count = 0
for line in fh:
    if count > 200 : break
    address = line.strip()
    print ('')
    cur.execute("SELECT geodata FROM Locations WHERE address= ?", ((address), ))

    try:
        data = cur.fetchone()[0]
        print ("Found in database ",address)
        continue
    except:
        pass

    print ('Resolving', address)
    url = serviceurl + urllib.parse.urlencode({"sensor":"false", "address": address})
    print ('Retrieving', url)
    uh = urllib.request.urlopen(url, context=scontext)
    data = uh.read()
    print ('Retrieved',len(data),'characters',data[:20].replace('\n',' '))
    count = count + 1
    try: 
        js = json.loads(str(data))
        # print js  # We print in case unicode causes an error
    except: 
        continue

    if 'status' not in js or (js['status'] != 'OK' and js['status'] != 'ZERO_RESULTS') : 
        print ('==== Failure To Retrieve ====')
        print (data)
        break

    cur.execute('''INSERT INTO Locations (address, geodata) 
            VALUES ( ?, ? )''', ( buffer(address),buffer(data) ) )
    conn.commit() 
    time.sleep(1)

print ("Run geodump.py to read the data from the database so you can visualize it on a map.")

我用以下代码排序:

print('检索',len(数据),'字符',数据[:20] .decode()。replace('\\ n',''))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM