【问题标题】:Finding words in a file in which all characters are contained in another word在文件中查找所有字符都包含在另一个单词中的单词
【发布时间】:2017-08-21 03:53:05
【问题描述】:

所以我正在这样做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包含一个简短的sn-p它的单词列表

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

【问题讨论】:

  • 既然你是新人,你应该看看this。

标签: python file for-loop


【解决方案1】:

只需使用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()

【讨论】:

  • 试过效果不好 validword=[] s=list(args.word) for wordlist:piece=True for letter in word: if letter not in s:piece=False elif 片段:s.remove(letter) total=0 for i in s: total=total+scores[letter] validword.append([total,word]) 但是如果我使用 ASADEF 作为我的机架,我的输出仍然是错误的,我得到 0单词是 sab 2,单词是 ea 4,单词是 aa
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多