split,rstrip的使用,附加在列表中

时间:2017-02-14 01:50:33

标签: list sorting split append

本周的作业是一个关于列表的问题,我无法摆脱列表符号。

打开文件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

1 个答案:

答案 0 :(得分: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

从用户请求文件名的替代解决方案,使用continue并与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