2016-07-06 72 views
1

我正在做一个小项目,在这个项目中我的程序解开一个字符串并找到它的每个可能的组合。从另一个列表中寻找一个字符串对象

我有两个列表; comboListwordListcomboList拥有这个词的每个组合;例如,为comboList'ABC'

['ABC','ACB','BAC','BCA','CAB','CBA'] 

(仅'CAB'是一个真正的字)

wordList持有56,000字从文本文件导入。这些都在英语词典中找到并按长度排序,然后按字母顺序排列。

isRealWord(comboList,wordList)是我的功能,通过检查它是否在wordList中来测试comboList中哪些单词是真实的。下面的代码:

def isRealWord(comboList, wordList): 
    print 'Debug 1' 
    for combo in comboList: 
     print 'Debug 2' 
     if combo in wordList: 
      print 'Debug 3' 
      print combo 
      listOfActualWords.append(combo) 
    print 'Debug 4' 

这是输出:

run c:/Users/uzair/Documents/Programming/Python/unscramble.py 
Please give a string of scrambled letters to unscramble: abc 
['A', 'B', 'C'] 
['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'] 
Loading word list... 
55909 words loaded 
Debug 1 
Debug 2 
Debug 2 
Debug 2 
Debug 2 
Debug 2 
Debug 2 
Debug 4 
[] 

为什么if combo in wordList没有返回True,如何解决?

+6

wordlist是否全部大写呢? – L3viathan

+2

您可以使用>> print“{0}:{1}”替换您的isRealWord方法中的调试2行。format(combo,wordList)并查看究竟是什么被比较 - 好的调试不错 - wordList是一大堆字..但打印你的组合,看看它的检查到底是什么! – AK47

+0

附注:使用'set'来保存'wordList'会更快!如果您需要'wordList'作为包含代码的'list',那么每次都可能在'isRealWord'里面创建'set'。 – MisterMiyagi

回答

1

我认为这里的问题是,你比较两个字符串相同的字母,但混合下/大案例
,看看我是否是正确的尝试将所有的字转换成wordList为大写,然后在isRealWord用大写的字比较(只是要确定)如下:

UpperCaseWordList = [word.upper() for word in wordList] 
... 
def isRealWord(comboList, wordList): 
    for combo.upper() in comboList: 
     if combo in wordList: 
      print combo 
      listOfActualWords.append(combo) 
+0

我认为你需要将'wordList'参数改为'UpperCaseWordList' –

+0

请注意,'wordList'现在是一个方法中的一个参数 - 所以我认为调用将是这样的:'isRealWord(comboList,UpperCaseWordList) –

2

我建议使用set,因为它的实现会更快。有set.intersection方法。这里是一个不区分大小写的解决方案:

listOfActualWords = set.intersection(set(word.upper() for word in comboList), set(word.upper() for word in wordList)) 
相关问题