在文件中查找所有字符都包含在另一个单词中的单词

时间:2017-08-21 03:53:05

标签: python file for-loop

所以我正在做这个http://wiki.openhatch.org/Scrabble_challenge#Step_3:_find_valid_words并且我已经陷入了一个部分。我正在尝试使用嵌套循环遍历单词列表中的每个单词(我打开的文本文件),并且对于该单词中的每个字母,查看该字母是否包含在用户输入中。到目前为止,我的代码是

import argparse
import sys

file=open('sowpods.txt','r')#opens the file of words used in scrabble
scores = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
         "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
         "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
         "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
         "x": 8, "z": 10}#dictionary for letter values
parser=argparse.ArgumentParser(description='designed to help in scrabble')
#command line interface using argparse module
parser.add_argument("word",help="input your letters",nargs='?')#adds the 
positional argument with description
args=parser.parse_args()

if args.word is None:
    print('error I need letters to work')
    sys.exit()
else:
    print(str.lower(args.word))#converts the the input for argument word 
into lowercase letters
for letter in file:
    i=str.lower(letter)
    for i in args.word:
        valid=[]
        valid.append(i)
        print(valid)

预期输出应如下所示

python scrabble.by ZZAAEEI
size
ziz

基本上是有效单词的列表。

一旦我有了这个列表,我就可以使用得分词典获得该词的价值,但我被卡住了,因为我认为嵌套循环是最好的方法。谢谢你的帮助。

文件sowpods.txt包含一个单词列表,它是一个简短的片段

AA AAH AAHED AAHING AAHS AAL AALII AALIIS AALS AARDVARK AARDVARKS AARDWOLF AARDWOLVES AARGH AARRGH AARRGHH AARTI AARTIS AAS AASVOGEL AASVOGELS AB ABA ABAC ABACA ABACAS ABACI ABACK ABACS ABACTERIAL ABACTINAL ABACTINALLY a small snippet it's pretty much a file of all valid scrabble words

1 个答案:

答案 0 :(得分:2)

只需使用set difference操作:

word = args.word.lower()
valid = []
for line in file:
    line = line.lower().strip()
    if not (set(line) - set(word)):
        valid.append(i)

print(valid)

如果line包含word中包含的所有字符,则这两个字符之间的设置差异将为空集,因此not <empty set>True

我希望你文件中的每个单词都包含在一个单独的行中,否则如果有的话,这既不会有效也不会有效。

示例:

⇒ word = ZZAAEEI
  line = zeze

⇒ set_word = {'z', 'a', 'e', 'i'}
  set_line = {'z', 'e' }

⇒ set_line - set_word = {'z', 'e' } - {'z', 'a', 'e', 'i'} 

⇒ set()