首页 > 解决方案 > 为什么我会收到一条错误,说明在 Python 中强制转换为 unicode?

问题描述

我正在尝试编写一个代码,该代码将从我的 csv 中获取一个 api 作为输入:

from pyzillow.pyzillow import ZillowWrapper, GetDeepSearchResults, GetUpdatedPropertyDetails

def get_zillowinfo(address,zipcode):
    zillow_data = ZillowWrapper('X1-ZWz17seirkzuh7_93aho')
    deep_search_response = zillow_data.get_deep_search_results(address,zipcode)
    result1 = GetDeepSearchResults(deep_search_response) #get zillowid from address
    updated_property_details_response = zillow_data.get_updated_property_details(result1.zillow_id)
    result2 = GetUpdatedPropertyDetails(updated_property_details_response) # get detail property info
    result = result2.home_info
    return result

print get_zillowinfo('73 main blvd','01545')

#2
import csv
with open(r'C:\Users\bca\Desktop\Pricing Study-Zillow\sample4.csv', 'r') as csvfile:
    spamreader = csv.reader(csvfile,delimiter=',')
    next(spamreader)
    for row in spamreader:
        print row


#3
import csv
with open(r'C:\Users\bca\Desktop\Pricing Study-Zillow\sample4.csv', 'r') as csvfile:
    spamreader = csv.reader(csvfile,delimiter=',')
    next(spamreader)
    for row in spamreader:
            print get_zillowinfo(row[0],row[1])

当我执行第 3 步时,出现错误:

Traceback (most recent call last):

  File "C:\Users\bca\AppData\Local\Continuum\anaconda2\lib\site-packages\IPython\core\interactiveshell.py", line 2895, in run_code
    self.showtraceback()

  File "C:\Users\bca\AppData\Local\Continuum\anaconda2\lib\site-packages\IPython\core\interactiveshell.py", line 1828, in showtraceback
    self._showtraceback(etype, value, stb)

  File "C:\Users\bca\AppData\Local\Continuum\anaconda2\lib\site-packages\ipykernel\zmqshell.py", line 547, in _showtraceback
    u'evalue' : py3compat.safe_unicode(evalue),

  File "C:\Users\bca\AppData\Local\Continuum\anaconda2\lib\site-packages\ipython_genutils\py3compat.py", line 65, in safe_unicode
    return unicode_type(e)

TypeError: coercing to Unicode: need string or buffer, dict found

为什么会这样?是因为我的字符不是字符串吗?在这种情况下,如何将我的所有数据更改为字符串?

这是我的数据集的代表: 在此处输入图像描述

我需要在代码中进行哪些更改以避免该类型错误?

标签: pythonerror-handlingopencsv

解决方案


推荐阅读