Skip to content Skip to sidebar Skip to footer

Splitting A State Name With A City Name, Return A List Containing Both?

So this is the simplified version of the data file: Wichita, KS[3769,9734]279835 308 1002 1270 1068 1344 1360 1220 944 1192 748 1618 1774 416 1054 Wheeling, WV[4007,8072]43070 101

Solution 1:

Well since the data you've posted is showing just a two letter postal code after a , separator, I'd:

city, state = line.split(', ')
state = state[:2]
return (city, state)

If you've got some data that isn't a two letter postal code, I'd look for the expected [ character:

city, state = line.split(', ')
state = state[:state.index('[')
return (city, state)

To get the population, you'll need to make a dictionary of the stats you want to keep. And yes, I know it's ugly:

fin = open ("miles.txt","r")
stats={}
for line in fin:
    if line[0].isalpha(): #its got a city, state, x, y and pop stat to keep
        city, state = line.split(', ')
        state = state[ :state.index('[') ]
        #get the two elements around the commas within the square brackets
        lat, lng = line[ line.index('[') +1 : line.index(']') ].split(',')
        #get the element after the last right bracketpop = line[line.index(']') +1 :] 
        stats.update( {(city, state): (lat, lng, pop)} )
return stats

From there, you'll be able to toy around with the stats from your text file.

Just make sure you don't have key collisions...you have a tuple as your unique binding element for your stats...Keep in mind you wouldn't want to get data from a city name (there's more than one Springfield), but instead do a lookup on stats for the key matching (city, state). The value returned will be the x, y and population stats you had on that line.

>>>stats.get(('Waukegan, IL'))
(4236, 8783, 67653)
>>>stats.get(('Waukegan, IL'))[-1]
67653

Post a Comment for "Splitting A State Name With A City Name, Return A List Containing Both?"