2015-11-09 91 views
-2

我想解析文本文件的每一行,每一個類似於此:轉換文本文件到列表

New Mexico,Santa Fe 
Alabama,Montgomery 

我想解析每一行,讓我結束了這:

states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas'] 
cities = ['Montgomery', 'Juneau', 'Phoenix', 'Little Rock'] 

文本文件的內容已經被存儲在一個函數:f.read()和被定義爲:

#module imports 
import sys 
import random 

fname = sys.argv[1] 
with open(fname, 'r') as f: 
    print(f.read()) 
+0

你可以顯示你的代碼嗎?請說明哪些區域給您帶來困難。 – idjaw

+0

此外,您的主題行有點混亂。你說詞典(意思是python'dict'?),但是你會顯示兩個列表。給我們一些代碼,然後我們可以繼續。 – tdelaney

+0

代碼做什麼? @idjaw –

回答

1

你可以這樣說:

import sys 
states = [] 
cities = [] 
fname = sys.argv[1] 
f = open(fname, 'r') 
for line in f: 
    line = line.rstrip() # This will remove all the whitespaces at the end of the line 
    line = line.split(',') 
    states.append(line[0]) 
    cities.append(line[1]) 

print states 
print cities 
f.close() 
1

對您有幫助嗎?

>>> with open('file') as f: 
...  text = [i.strip() for i in f] 
...  
... 
>>> text 
['New Mexico,Santa Fe', 'Alabama,Montgomery'] 
>>> states = [] 
>>> cities = [] 
>>> for i in text: 
...  states.append(i.split(',')[0]) 
...  cities.append(i.split(',')[1]) 
...  
... 
>>> states 
['New Mexico', 'Alabama'] 
>>> cities 
['Santa Fe', 'Montgomery'] 
>>> 
+0

只需執行一次'split',您就可以在代碼中進行小型優化。 –

1

首先將其轉換爲一個字典。然後一個列表是字典的keys,另一個列表是字典的values

另外不要忘記在使用前檢查長度sys.argv

import sys 

if len(sys.argv) < 2: 
    print('must provide filename') 
    exit() 

with open(sys.argv[1], 'r') as f: 
    d = dict(reversed(line.strip().split(',')) for line in f) 

    cities = list(d.keys()) 
    states = list(d.values()) 

print('cities = %r' % cities) 
print('states = %r' % states) 

我加入了reversed,因爲它更有意義,有城市名稱爲重點和國家名稱作爲值。