python排序文本文件中的单词列表(test.txt)

时间:2015-06-09 01:09:23

标签: python python-2.7 python-3.x wxpython

我有一个UNICODE格式的5000个单词列表。 如何在添加新单词后对它们进行排序???

 a = []
    for word in text:
        if word not in dic:
            misspelled = word
            a.append(misspelled)             
            foo =misspelled
            f = open('test.txt', 'a')
            f.write(foo.encode('utf8'))
            x='\n'
            f.write(x.encode('utf8'))
            f.close()

2 个答案:

答案 0 :(得分:1)

只需对他们打电话.sort:

a.sort()

您还应该打开一次文件并使用with打开文件:

with  open('test.txt', 'w') as f:      
    for word in text:
        if word not in dic:
            misspelled = word
            a.append(misspelled)
            foo = misspelled
            ..........
    a.sort() # sort
    for word in a:
        f.write("{}\n".format(word))

答案 1 :(得分:0)

您可以使用当前的单词列表初始化a,然后像往常一样花费它,然后在将a写入文件之前对其进行排序。

f = file("test.txt", "r")
a = f.readlines()
. . . # Looping to find misspelled words, spending to a
f = file("test.txt", "w")
f.write("\n".join(sorted(a)).encode("utf-8")
f.close()