如何根据文本文件检查生成的字符串

How to check generated strings against a text file

我试图让用户输入一串带有一个星号的字符。星号表示可以替换为元音字母 (a、e、i、o、u) 的字符,以便查看哪些替换产生有效单词。 本质上,我想输入“l*g”并将其设置为 return“lag, leg, log, lug”,因为“lig”不是有效的英文单词。下面我有无效的单词表示为“x”。

我已经让它正确输出了每个可能的组合(例如,包括“lig”),但是一旦我尝试将这些词与我引用的文本文件(用于有效词列表)进行比较,它只有 return 5 行 x。我猜是我导入或读取文件不当?

这是我正在查看的文件的 link,因此您可以看到格式: https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/packages/corpora/words.zip 使用“en”文件~2.5MB

它不在字典布局中,即没有相应的 keys/values,只有行(也许我可以使用行号作为索引,但我不知道该怎么做)。我可以更改什么来检查测试词以根据文本文件缩小哪些是有效词?

with open(os.path.expanduser('~/Downloads/words/en')) as f:
    words = f.readlines()

inputted_word = input("Enter a word with ' * ' as the missing letter: ")
letters = []
for l in inputted_word:
    letters.append(l)

### find the index of the blank
asterisk = inputted_word.index('*') # also used a redundant int(), works fine


### sub in vowels
vowels = ['a','e','i','o','u']
list_of_new_words = []
for v in vowels:
    letters[asterisk] = v
    new_word = ''.join(letters)
    list_of_new_words.append(new_word)

for w in list_of_new_words:
    if w in words:
        print(new_word)
    else:
        print('x')

可能有更有效的方法来做到这一点,但我对此是全新的。最后两个 for 循环可能会合并,但这样调试起来会更困难。

print(list_of_new_words)

给予

['lag', 'leg', 'lig', 'log', 'lug']

到目前为止,还不错。

但是这个:

for w in list_of_new_words:
    if w in words:
        print(new_word)
    else:
        print('x')

这里打印new_word,这是在前面的for循环中定义的:

for v in vowels:
    letters[asterisk] = v
    new_word = ''.join(letters)  # <----
    list_of_new_words.append(new_word)

因此在循环之后,new_word 仍然具有分配给它的最后一个值:"lug"(如果脚本输入是 l*g)。
您的意思可能是 w 而不是 ?

for w in list_of_new_words:
    if w in words:
        print(w)
    else:
        print('x')

但它仍然 prints 5 xs ...
所以这意味着 w in words 总是 False。怎么样?
看着 words :

print(words[0:10])  # the first 10 will suffice
['A\n', 'a\n', 'aa\n', 'aal\n', 'aalii\n', 'aam\n', 'Aani\n', 'aardvark\n', 'aardwolf\n', 'Aaron\n']

字典中所有单词的末尾都包含一个换行符 (\n)。我猜你不知道 readlines 是做什么的。所以我建议使用 :

words = f.read().splitlines()

相反。

经过这 2 次修改(wsplitlines):

Enter a word with ' * ' as the missing letter: l*g
lag
leg
x
log
lug