Python使用append删除重复单词从文件创建排序列表

时间:2015-07-29 01:58:46

标签: python python-2.7 sorting append

我目前正在进行python课程,但是在6小时后我就迷失了。分配指示学生创建一个程序,其中用户输入文件名,python打开文件并构建一个没有重复的排序单词列表。方向很清楚,必须使用For循环和追加。 “对于每行上的每个单词,检查该单词是否已经在列表中,如果没有将其附加到列表中。”

fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    line = line.strip()
    words = line.split()
for words in fh:
    if words in 1st:continue
        elif 1st.append
1st.sort()
print 1st 

2 个答案:

答案 0 :(得分:0)

不确定以下循环应该做什么 -

for words in fh:
    if words in 1st:continue
        elif 1st.append

上述操作无效,因为在控件到达此部分之前,您已经耗尽了文件fh

你应该在内部循环 - for line in fh: - 逐个覆盖words列表中的单词,如果它不存在则附加到lst

此外,您应该lst.append(word)

另外,我认为你的if..elif块也不是有效的语法。

你应该做像xample -

这样的事情
for line in fh:
    line = line.strip()
    words = line.split()
    for word in words:
        if word not in lst:
            lst.append(word)

答案 1 :(得分:0)

单独使用set()会更容易,但根据赋值指令,这将是一个很好的实现。与仅list版本相比,它真的很快!

from collections import Set

def get_exclusive_list(fname):
    words = []
    with open(fname.txt, 'r') as file_d:
        data = file_d.read()
    [words.extend(li.split(' ')) for li in data.splitlines()]
    data = []
    already_seen = set()
    for thing in words:
        if thing not in already_seen:
            data.append(thing)
            already_seen.add(thing)
return data


# The better implementation
def get_exclusive_list_improved(fname):
    words = []
    with open(fname.txt, 'r') as file_d:
        data = file_d.read()
    [words.extend(li.split(' ')) for li in data.splitlines()]
    return list(set(words))