我正在尝试读取文件中的行,将行拆分为单词,然后将单个单词添加到列表中(如果它们不在列表中)。最后,必须对单词进行排序。一段时间以来,我一直在努力做到这一点,并且我理解这些概念,但我不确定如何正确地使用确切的语言和位置。这是我拥有的:
filename = raw_input("Enter file name: ")
openedfile = open(filename)
lst = list()
for line in openedfile:
line.rstrip()
words = line.split()
for word in words:
if word not in lst:
lst.append(words)
print lst
最佳答案
如果您要根据空格将文本文件拆分为单词,只需对整个文件使用 split()
即可。阅读每一行并将其剥离不会有任何收获,因为 split()
已经处理了所有这些。
因此,要获得初始单词列表,您只需要:
filename = raw_input("Enter file name: ")
openedfile = open(filename)
wordlist = openedfile.read().split()
然后要删除重复项,将单词列表转换为集合:
wordset = set(wordlist)
最后排序:
words = sorted(wordset)
这一切都可以简化为三行,如下所示:
filename = raw_input("Enter file name: ")
with open(filename) as stream:
words = sorted(set(stream.read().split()))
(注意:with
语句会自动为您关闭文件)
关于python - 如何在删除重复单词并在 Python 中对列表进行排序的同时将文本文件转换为列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31410047/