Python 消除基于字母的单词
我有一本字典和一个字母表:Python 消除基于字母的单词,python,Python,我有一本字典和一个字母表: import string alphabet = list(string.ascii_lowercase) dictionary = [line.rstrip('\n') for line in open("dictionary.txt")] 在函数中,我从字母表中删除一个字母 alphabet.remove(letter) 现在,我想通过字典过滤掉那些不在字母表中的单词 我尝试了循环: for term in dictionary: for ch
import string
alphabet = list(string.ascii_lowercase)
dictionary = [line.rstrip('\n') for line in open("dictionary.txt")]
在函数中,我从字母表中删除一个字母
alphabet.remove(letter)
现在,我想通过字典过滤掉那些不在字母表中的单词
我尝试了循环:
for term in dictionary:
for char in term:
print term, char
if char not in alphabet:
dictionary.remove(term)
break
然而,这跳过了某些单词。
我试过过滤器:
dictionary = filter(term for term in dictionary for char in term if char not in alphabet)
但我得到了一个错误:
SyntaxError: Generator expression must be parenthesized if not sole argument
您不希望在迭代列表(或任何容器)时对其进行修改。这可能会导致一些项目被跳过的错误。如果你复制了一份(
字典[:]
),它应该是
for term in dictionary[:]:
for char in term:
print term, char
if char not in alphabet:
dictionary.remove(term)
break
我们在这里也可以做得更好
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)]
另外,避免使用
列表
实例的名称dictionary
可能是明智的,因为dict
实际上是一种内置类型…在对列表(或任何容器)进行迭代时,您不想修改它。这可能会导致一些项目被跳过的错误。如果你复制了一份(字典[:]
),它应该是
for term in dictionary[:]:
for char in term:
print term, char
if char not in alphabet:
dictionary.remove(term)
break
我们在这里也可以做得更好
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)]
另外,对于
列表
实例,避免使用名称dictionary
可能是明智的,因为dict
实际上是一种内置类型…那么提供给filter的函数呢?dictionary在Python中有非常特殊的含义。考虑使用另一个变量名来避免混淆。提供给筛选器字典的函数在Python中有什么特别的含义。考虑使用另一个变量名来避免混淆。