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

2024-06-07 19:11:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Youngstown, OH[4110,8065]115436
Yankton, SD[4288,9739]12011
966
Yakima, WA[4660,12051]49826
1513 2410
Worcester, MA[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()

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

任何帮助都将不胜感激,谢谢大家。在


Tags: 文件in名称信息forlinesdoh
1条回答
网友
1楼 · 发布于 2024-06-07 19:11:51

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

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

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模块和regex模式来实现这一点。在

相关问题 更多 >

    热门问题