2017-04-17 61 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'