How do I read from a file consists of city names and coordinates/Populations and create functions to get the coordinates and population?

后端 未结 1 1833
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 09:26

I\'m using Python, and I have a file which has city names and information such as names, coordinates of the city and population of the city:

Youngstown, O

相关标签:
1条回答
  • 2021-01-29 09:40

    I am feeling generous since you responded to my comment and made an effort to provide more info....

    Your code example isn't even runnable right now, but from a purely pseudocode standpoint, you have at least the basic concept of the first part right. Normally I would want to parse out the information using a regex, but I think giving you an answer with a regex is beyond what you already know and won't really help you learn anything at this stage. So I will try and keep this example within the realm of the tools with which you seem to already be familiar.

    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
    

    Even though I have provided a full code solution for you, I am hoping that it will be more of a learning experience with the added comments. Eventually you should learn to do this using the re module and a regex pattern.

    0 讨论(0)
提交回复
热议问题