2012-11-25 64 views
1

因此,對於一些背景:我一直在努力學習python,並花了一些時間嘗試做一些有趣的事情,我碰到了有關daniweb的建議,嘗試創建一個程序,在其中輸入一個字符列表,然後打印出包含所有這些字符的任何單詞。字符集搜索字符串

我已經找到了如何做手工,這裏的下面的代碼:

string = raw_input("Please enter the scrable letters you have: ") 
for line in open('/usr/share/dict/words', 'r').readlines(): 
    if string[0] in line and string[1] in line and string[2] in line: 
     print line, 

但我有點無法弄清楚如何得到它通過使用循環(這種方式,用戶可以輸入工作。任意長度的字符的列表,我想通類似下面的工作,但它似乎沒有這樣做:

while i < len(string)-1: 
    if string[i] in line: tally = tally + 1 
    i = i + 1 
if tally == len(string)-1: print line 
else: i = 0 

在正確的方向上沒有任何幫助,將不勝感激,謝謝

+0

變化'如果符合= LEN(字符串) - 1'到'if tally = len(string)' – inspectorG4dget

+0

仍然不起作用,它出於任何原因打印任何包含字符串中任何一個字符的單詞。 – downvoteme

+0

你能舉個例子說明'/ usr/share/dict/words'是什麼嗎? –

回答

0

Set操作都可以在這裏派上用場:

inp = set(raw_input("Please enter the scrable letters you have: ")) 
with open('/usr/share/dict/words', 'r') as words: 
    for word in words: 
     if inp <= set(word): 
      print word, 
+0

啊,是的,我偶然發現了一些套裝,但是我現在正在以一種錯綜複雜的方式去看待它們。這工作。謝謝。 – downvoteme

3

我會用一切與這個理解... ...和理解是一個循環

user_string = raw_input("Please enter the scrable letters you have: ") 
for line in open('/usr/share/dict/words', 'r').readlines(): 
    if all(c in line for c in user_string): 
     print line, 
+0

這也給我沒有輸出。我使用OSX 10.8.2並使用Python 2.7.2,如果這仍然有效? – downvoteme