python - 从坐标创建字典的脚本?

标签 python dictionary geocode

新来的,这是我的第一篇文章。

我有一个正在处理的 python 脚本,该脚本的主要目的是从我计算机上的 .txt 文件中获取城市列表,并让脚本生成一个字典,其中的键是城市名称值是作为点对象的位置。此外,我必须获取点对象字典和新文件位置,并将新值写入文本文件,其中包含行中的数据(字典中坐标旁边的城市名称)。

在过去的 2 周里,我实际上已经在这上面花费了大约 30 个小时,但仍然没有运气让它完全发挥作用。现在,城市名称和坐标将在 python shell 中打印出来,只有城市名称会打印到文本文件中,但我无法将城市名称和坐标组合在一个字典中打印成一个文本文件。

我正在使用一个名为 locations.pyc 的 python 模块,这个模块的目的是连接到互联网、谷歌服务器,然后引入与列表中城市名称相关的坐标。这些城市都在阿拉斯加..

这是目前为止的脚本。

import location         # calls the location module in file


def getFileList(path):
    f = open(path, "r")
    f.readline()
    fileList = []       # removes column header
    for line in f:
        fileList.append(line.strip())
    f.close()
    return fileList


class Point:
    def __init__(self, x = 0, y = 0):
        self.x = float(x)
        self.y = float(y)


def makeCitiesDict(citiesList):
    CitiesDict = dict()
    for city in citiesList:
        loc = location.getaddresslocation(city)
        x = loc[0]
        y = loc[1]
        CitiesDict[city] = Point(x, y)

    return CitiesDict

def writeDictFile(aDict):
    txt_file = open(r"Alaska.txt",'w')
    txt_file.writelines(myCitiesDict)
    txt_file.close()

myCities = getFileList(r"cities_Small.txt")

myCitiesDict = makeCitiesDict(myCities)
writeDictFile("myCitiesDict\n")   

print myCitiesDict

for key in myCitiesDict:
    point = myCitiesDict[key]
    print point.x,point.y

这是用于运行脚本的 locations.pyc 模块的链接。 location.pyc

最佳答案

当你传递你当前的大字典时,你当前版本的 writeDictFile 将失败并出现错误:

TypeError: writelines() argument must be a sequence of strings

要解决它,您可以做几件事:

  1. 手动遍历字典中的键值对并将它们手动写入文件:

    def write_to_file(d):
        with open(outputfile, 'w') as f:
            for key, value in d.items():
                f.write('{}\t{}\t{}\n'.format(key, value.x, value.y))
    
  2. 使用 csv module为您完成工作。但是,在这种情况下,您需要将单个大词典转换为小词典列表:

    def makeCitiesDict(citiesList):
        citylist = []
        for city in citiesList:
            loc = location.getaddresslocation(city)
            x = loc[0]
            y = loc[1]
            citylist.append({'cityname': city, 'lon': x, 'lat': y})
        return citylist
    
    
    def writeDictFile(biglist):
        with open(outputfile, 'w') as f:
            dw = csv.DictWriter(f, fieldnames=('lon', 'lat', 'cityname'), delimiter='\t')
            dw.writerows(biglist)
    

顺便说一句,python 编码约定建议不要对函数名称使用驼峰命名法。看看PEP8如果你有兴趣。

关于python - 从坐标创建字典的脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28650264/

相关文章:

python - Django 模板 "for loops"无法正常工作

sql - 查询地理编码位置(纬度/经度)周围的周长

python - 如何在Python中对大量点进行反向地理编码?

python - 属性错误 : 'module' object has no attribute 'urlopen'

python - 如何在Python中解码/编码十进制值?

python-2.7 - ititems的优势是什么?

用于打印的 Python 字典键格式不适用于数字字符串

Swift:用于地理编码的递归异步循环

python - 使用 BeautifulSoup 下载图像

python - 如何将数据从嵌套 JSON 文件导入到 CSV?