消除基于字母的单词

Jos*_*shK 0 python

我有一本字典和一个字母表:

import string
alphabet = list(string.ascii_lowercase)
dictionary = [line.rstrip('\n') for line in open("dictionary.txt")]
Run Code Online (Sandbox Code Playgroud)

在函数中,我从字母表中删除一个字母

alphabet.remove(letter)
Run Code Online (Sandbox Code Playgroud)

现在,我想过滤字典以消除包含不在字母表中的字母的单词。

我试过循环:

for term in dictionary:
        for char in term:
            print term, char
            if char not in alphabet:
                dictionary.remove(term)
                break
Run Code Online (Sandbox Code Playgroud)

但是,这会跳过某些单词。我试过过滤器:

dictionary = filter(term for term in dictionary for char in term if char not in alphabet)
Run Code Online (Sandbox Code Playgroud)

但我收到错误:

SyntaxError: Generator expression must be parenthesized if not sole argument
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 5

在迭代列表时,您不想修改列表(或实际上任何容器)。这可能会导致错误,似乎有些项目被跳过。如果您复制 ( dictionary[:]),它应该会解决...

for term in dictionary[:]:
    for char in term:
        print term, char
        if char not in alphabet:
            dictionary.remove(term)
            break
Run Code Online (Sandbox Code Playgroud)

我们也可以在这里做得更好......

alphabet_set = set(alphabet)  # set membership testing is faster than string/list...
new_dictionary = [
    term for term in dictionary
    if all(c in alphabet_set for c in term)]
Run Code Online (Sandbox Code Playgroud)

此外,它可能是明智的,避免了名dictionarylist情况下,因为dict实际上是一个内置式...