2015-06-09 48 views
0

我有一个UNICODE格式5000个单词的列表。 如何在添加新单词后对它们进行排序?python排序文本文件中的单词列表(test.txt)

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() 

回答

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)) 
+0

我,但是当我打开文本文件我没有看到变化和新的字被插入到列表@padraic –

+0

@BamoNabaz的最后一行,也就是'了'呢,则追加到一个文件 –

+0

我读了OP的代码和你的,OP似乎有一个额外的'f.write(x.encode('utf8'))''。它甚至需要吗? –

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() 
相关问题