错误:' str' object不支持python中的项目赋值

时间:2016-03-10 16:52:26

标签: python geopy

我正在尝试使用从github下载的一些代码来使用geopy对地址进行地理编码。 但是代码的错误是str obj不支持geocode_addresses address_dict["error"] = ""中的项目分配? 为什么我会收到这个错误。下面是代码。

if __name__ == '__main__':
    csv_file = 'nr-fixedNew.csv'
    with open(csv_file, 'rb') as csvfile:
        for row in csvfile.readlines():
            df = pd.read_csv(csv_file)
            address = df.ADDRESS
            geocoded = geocode_addresses(address)
            write_csv(output_file, geocoded)


    def geocode_addresses(address_dicts):
        geocoder = geocoders.GoogleV3()
        for address_dict in address_dicts:
            address_dict["error"] = ""
            try:
                time.sleep(1)
                address, (lat, lon) = geocoder.geocode(address_dict["fulladdress"])
                address_dict["fulladdress"] = address
                address_dict["latitude"] = lat
                address_dict["longitude"] = lon
            except ValueError as e:
                address_dict["error"] = e
        return address_dicts

数据集示例

SEX,PROGRAMME,ADDRESS
M,2,"J6855, JALAN LMBAH KESANG 1/1-3,77378 MERLIMAU, MELAKA";

1 个答案:

答案 0 :(得分:0)

在下面的代码段中,它看起来像address / df.ADDRESS

    address = df.ADDRESS
    geocoded = geocode_addresses(address)

address不是像您期望的那样的词典列表:

for address_dict in address_dicts:
    address_dict["error"] = ""

在测试代码之后,这是address_dicts

(<class 'pandas.core.series.Series'>

基本上是一个(pandas)字符串列表:

(Pdb) address_dicts
0    J6855, JALAN LMBAH KESANG 1/1-3,77378 MERLIMAU...
Name: ADDRESS, dtype: object
(Pdb) address_dicts[0]
'J6855, JALAN LMBAH KESANG 1/1-3,77378 MERLIMAU, MELAKA;'

因此,您的问题与解析CSV文件的方式有关。

而且,我真的不明白你在这里要做什么:

with open(csv_file, 'rb') as csvfile:
    for row in csvfile.readlines():
        df = pd.read_csv(csv_file)

所以你打开文件,然后迭代文件,对于每一行,你将文件解析为csv?!

if __name__ == '__main__':
    csv_file = 'nr-fixedNew.csv'
    with open(csv_file, 'rb') as csvfile:
            df = pd.read_csv(csv_file).to_dict() ### here you convert to dict
            address = df['ADDRESS']
            geocoded = geocode_addresses(address)
            write_csv(output_file, geocoded)

然后你需要重新思考解析值的方式。不要犹豫,拨打pdb或添加打印输出。