如何从文件中读取包含城市名称和坐标/人口并创建函数以获取坐标和人口?

时间:2012-03-22 16:39:54

标签: python

我正在使用Python,我有一个文件,其中包含城市名称和信息,例如姓名,城市坐标和城市人口:

  

Youngstown,OH [4110,8065] 115436
  Yankton,SD [4288,9739] 12011
  966个
  亚基马,华盛顿州[4660,12051] 49826
  1513 2410
  伍斯特,马萨诸塞州[4227,7180] 161799
  2964 1520 604
  Wisconsin Dells,WI [4363,8977] 2521
  1149 1817 481 595

如何创建一个功能来获取城市名称并返回包含给定城市的纬度和经度的列表?

fin = open ("miles.dat","r")
def getCoordinates 
cities = []
for line in fin:
    cities.append(line.rstrip())
    for word in line:
        print line.split()

这就是我现在尝试的;如何通过调用城市的名称来获取城市的坐标,如何返回每行的字而不是字母?

非常感谢任何帮助,谢谢大家。

1 个答案:

答案 0 :(得分:1)

我感到很慷慨,因为你回复了我的评论并努力提供更多信息......

您的代码示例现在甚至无法运行,但从纯伪代码的角度来看,您至少具有第一部分的基本概念。通常我想用正则表达式解析信息,但我认为给你一个正则表达式的答案超出你已经知道的范围,并且在这个阶段不会真正帮助你学习任何东西。因此,我将尝试将此示例保留在您似乎已熟悉的工具领域内。

def getCoordinates(filename):
    ''' 
    Pass in a filename.
    Return a parsed dictionary in the form of:

    {
        city:  [lat, lon]
    } 
    '''

    fin = open(filename,"r")
    cities = {}

    for line in fin:

        # this is going to split on the comma, and
        # only once, so you get the city, and the rest
        # of the line
        city, extra =  line.split(',', 1)

        # we could do a regex, but again, I dont think
        # you know what a regex is and you seem to already
        # understand split. so lets just stick with that

        # this splits on the '[' and we take the right side
        part = extra.split('[')[1]

        # now take the remaining string and split off the left
        # of the ']'
        part = part.split(']')[0]

        # we end up with something like: '4660, 12051'
        # so split that string on the comma into a list
        latLon = part.split(',')

        # associate the city, with the latlon in the dictionary
        cities[city] = latLong

    return cities

尽管我已经为您提供了完整的代码解决方案,但我希望通过添加的评论更多的是学习经验。最后,您应该学会使用re模块和正则表达式模式执行此操作。