搜索字符集的字符串

时间:2012-11-25 03:49:18

标签: python python-2.7

所以对于某些背景:我一直在努力学习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

非常感谢任何正确方向的帮助,谢谢。

2 个答案:

答案 0 :(得分: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,

答案 1 :(得分: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,
相关问题