2013-09-26 34 views
0

正在从本书的思考python中尝试此练习。 编写一个从文件中读取单词列表的程序(参见9.1节),并打印所有字母集合。Think Python Ch12 Ex 4:代码看起来正确但编译时挂起

我的策略是获取文件,对每个单词进行排序并存储在一个字符串列表(称为listy)中。然后,我会再次查看单词的原始列表,并与listy进行比较。如果相同,则将已排序的单词作为键和未排序的单词从原始文件存储为字典中的值。然后只需打印出每个键下的所有值。他们应该是anagrams。

我创建的第一个函数是生成listy。已经打破了代码,并检查它,似乎很好。但是,当我编译并运行它时,python会挂起,就像遇到无限循环一样。谁能告诉我这是为什么?

def newlist(): 
    fin = open('words.txt') 
    listy = [] 
    for word in fin: 
     n1 = word.strip() 
     n2 = sorted(n1) 
     red = ''.join(n2) 
     if red not in listy: 
      listy.append(red) 

    return listy 

newlist() 
+0

我无法重现的窍门。你能显示有问题的words.txt吗? – rerx

回答

0

使用set检查单词是否已经preocessed与否:

def newlist(): 
    with open('words.txt') as fin: 
     listy = set() 
     for word in fin: 
      n1 = word.strip() 
      n2 = sorted(n1) 
      red = ''.join(n2) 
      listy.add(red) 
    return listy 

newlist() 

你甚至可以把它写成:

def newlist(): 
    with open('words.txt') as fin: 
     return set(''.join(sorted(word.strip())) for word in fin) 

newlist()