2012-03-23 62 views
0

因此,這是數據文件的簡化版本:用城市名稱拆分州名,返回包含兩者的列表?

Wichita, KS[3769,9734]279835 
308 1002 1270 1068 1344 1360 1220 944 1192 748 1618 1774 416 1054 
Wheeling, WV[4007,8072]43070 
1017 1247 269 255 1513 327 589 203 1311 416 627 605 2442 998 85 
West Palm Beach, FL[2672,8005]63305 
1167 1550 1432 965 1249 2375 1160 718 1048 2175 760 1515 1459 3280 1794 1252 
Wenatchee, WA[4742,12032]17257 
3250 2390 1783 1948 2487 2595 1009 2697 2904 2589 1394 2690 1765 2912 117 1461 
2358 
Weed, CA[4142,12239]2879 
622 3229 2678 1842 1850 2717 2898 1473 2981 3128 2880 1858 2935 2213 3213 505 
1752 2659 
Waycross, GA[3122,8235]19371 
2947 2890 360 820 1192 1097 605 904 2015 828 386 703 1815 413 1155 1127 
2920 1434 899 
Wausau, WI[4496,8964]32426 
1240 2198 1725 1600 708 841 1138 805 913 848 1015 1222 907 646 1008 111 
1230 1777 509 676 
Waukegan, IL[4236,8783]67653 
244 1000 2260 1933 1360 468 757 1023 565 673 1056 775 982 667 854 768 
170 990 1985 551 436 
Watertown, SD[4490,9711]15649 
601 393 1549 1824 1351 1909 1058 572 880 1155 1263 534 1365 1572 1257 394 
1358 433 1580 1403 156 1026 

這裏是我現在的代碼......我現在可以從該行現在分成城市和國家的名字,但我如何獲得通過調用城市名稱來調用城市座標,以及如何通過調用城市名稱來獲取城市人口?例如:[x,y]是座標,並且[]之後的數字是羣體....

fin = open ("miles.txt","r") 
    cities=[] 
    for line in fin: 
     A=line.split() 
     if A[0][0] not in '': 
      B= A[0] + A[1][0]+ A[1][1] 
      cities.append[B] 
    print cities 

謝謝!任何幫助將不勝感激!

+0

這項工作是否會返回(r'(。*?)\ [',st)'output ='['Watertown,SD']'。 – RanRag 2012-03-23 05:06:15

+0

這很奇怪。這看起來很像一個http://stackoverflow.com/questions/9826669/how-do-i-read-from-a-file-consists-of-city-names-and-coordinates-populations-and/9827258的副本#9827258 – jdi 2012-03-23 06:26:40

+0

這是我@jdi我沒有按照你的程序對不起....我寫了自己的代碼,並再次卡住... – Braybray 2012-03-23 06:54:31

回答

1

那麼既然你已經發布的數據則呈現出,分離後,短短兩個字母的郵政編碼,我想:

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

如果你有一些數據,不是一個兩個字母郵政編碼,我會尋找預期[字符:

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

要獲得人口,你需要讓你想保持統計的字典。 是的,我知道這是醜陋:

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 bracket 
     pop = line[line.index(']') +1 :] 
     stats.update({(city, state): (lat, lng, pop)}) 
return stats 

從那裏,你將能夠玩具與stats從文本文件周圍。

只要確保你沒有關鍵的碰撞...你有一個元組作爲你的統計數據的獨特綁定元素...請記住,你不想從城市名稱(有不止一個斯普林菲爾德),而是做一個關鍵匹配(city, state)的統計查詢。返回的value將是您在該行上的x,y和人口統計數據。

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

謝謝......我現在知道如何工作,但我如何通過調用城市名稱來返回人口和座標? – Braybray 2012-03-23 05:17:25

+0

爲您更新。讓我知道這個是否奏效。 – Droogans 2012-03-23 05:30:18

+0

正在處理它..預先感謝.. – Braybray 2012-03-23 05:42:54