最近在coursera上自学python,有一个作业不太懂,想问问大家,这是作业要求:
Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order. 即把一段文字拆分为单词,然后按照首字母排列,如果没有的单词再补上。
这是标准答案:
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
words = list()
for line in fh:
words = line.split()
for word in words:
if lst.count(word) == 0:
lst.append(word)
lst.sort()
print(lst)
我的疑惑是:正确答案的code是怎么把重复的单词筛掉的呢?因为原文字中有重复的单词,但是出来的结果中没有。
Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order. 即把一段文字拆分为单词,然后按照首字母排列,如果没有的单词再补上。
这是标准答案:
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
words = list()
for line in fh:
words = line.split()
for word in words:
if lst.count(word) == 0:
lst.append(word)
lst.sort()
print(lst)
我的疑惑是:正确答案的code是怎么把重复的单词筛掉的呢?因为原文字中有重复的单词,但是出来的结果中没有。
