2017-04-17 66 views
1

我是非常業餘的python,目前我正在打開文件,讀取它並打印內容。基本上我想從一個文件中的內容打印成表包含此:在列表(表)列表中打印字符串

South Africa:France 
Spain:Chile 
Italy:Serbia 

,這裏是我的代碼,我在工作:

fileName = input("Enter file name:") 
openFile = open(fileName) 
table = [] 

for contents in openFile: 
    ListPrint = contents.split() 
    table.append(ListPrint) 
print(table) 

這樣做後,我得到了我想要的是在表格形式由列表組成。但是,我擔心的事情是它打印像這樣的字符串「南非」:

['South','Africa:France'] 

在那裏,我可以編寫蟒蛇給我提供任何方法:

['South Africa:France'] 

非常感謝任何幫助。

+0

如果你在一起配對我推薦使用字典。但取決於文件內容的外觀,很難告訴你如何處理它。如果每行都是一對,並且它們被分隔開來,我會用它作爲分隔符來分割。 – Aklys

回答

0

首先,剪貼列表想法該列表/列表。你想要一本字典。 其次,你用空格分割你的字符串,但是你需要用:字符來分割它。

>>> with open('file.txt') as f: 
...  countries = {} 
...  for line in f: 
...   first, second = line.strip().split(':') 
...   countries[first] = second 
... 
>>> countries 
{'Italy': 'Serbia', 'Spain': 'Chile', 'South Africa': 'France'} 
>>> countries['South Africa'] 
'France'