8.4
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.
You can download the sample data athttp://www.pythonlearn.com/code/romeo.txt
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line=line.rstrip()
a=line.split()
lst.append(a)
l2=list()
for i in range(len(lst)):
l2=l2+lst[i]
l2=list(set(l2))
l2.sort()
print l2
本文介绍如何使用Python打开并逐行读取一个名为'romeo.txt'的文件,通过split()方法将每一行拆分为单词列表,并检查每个单词是否已经存在于当前单词列表中。如果不存在,则将其添加到列表中。最后,程序会输出排序后的所有唯一单词。
3243

被折叠的 条评论
为什么被折叠?



