2017-02-14 84 views
2

本周的分配是一个关于列表的问题,我无法摆脱列表符号。分割,rstrip,追加列表的使用

打开文件romeo.txt并逐行阅读。对于每一行,使用split()方法将行分割成单词列表。该程序应该建立一个单词列表。对于每行上的每个单词,检查单词是否已经在列表中,并且是否将其附加到列表中。程序完成后,按字母顺序对结果词进行排序和打印。

http://www.pythonlearn.com/code/romeo.txt

fname = raw_input("Enter file name: ") 
fh = open(fname) 
lst = list() 
for line in fh: 
    line = line.split() 
    lst.append(line) 
    lst.sort() 
print lst 
+0

通过使用加入摆脱[] ''。加入(LST)。此外,如果你想检查重复,你最好使用一套,而不是使用列表。 –

回答

0

正如在评论中提到一个set会为了这个美好的,但由于分配约为名单,可以是这样的:

list_of_words = [] 
with open('romeo.txt') as f: 
    for line in f: 
     words = line.split() 
     for word in words: 
      if word not in list_of_words: 
       list_of_words.append(word) 

sorted_list_of_words = sorted(list_of_words) 
print(' '.join(sorted_list_of_words)) 

输出:

Arise But It Juliet Who already and breaks east envious fair grief is kill light moon pale sick soft sun the through what window with yonder 

从用户请求的文件名的替代解决方案,采用继续并且是与Python 2.x的兼容:

fname = raw_input('Enter file: ') 

wordlist = list() 
for line in open(fname, 'r'): 
    words = line.split() 
    for word in words: 
     if word in wordlist: continue 
     wordlist.append(word) 

wordlist.sort() 
print ' '.join(wordlist) 

输出:

Enter file: romeo.txt 
Arise But It Juliet Who already and breaks east envious fair grief is kill light moon pale sick soft sun the through what window with yonder