Par*_*gue 3 python string loops list
我有一个填充了字典中的单词的列表.我想找到一种方法来删除所有单词,只考虑在目标单词开头形成的根单词.
例如,单词"rodeo"将从列表中删除,因为它包含英语有效单词"rode"."打字机"将被删除,因为它包含英文有效的单词"type".但是,单词"snicker"仍然有效,即使它包含单词"nick",因为"nick"位于单词的中间而不是单词的开头.
我在想这样的事情:
for line in wordlist:
if line.find(...) --
Run Code Online (Sandbox Code Playgroud)
但是我希望那个"if"语句然后遍历列表中的每个单词检查它是否找到它,如果是,则从列表中删除它自己,这样只剩下根词.我是否必须创建wordlist的副本才能遍历?
因此,您有两个列表:要检查和可能删除的单词列表,以及有效单词列表.如果您愿意,可以将相同的列表用于这两个目的,但我假设您有两个列表.
对于速度,您应该将有效单词列表转换为集合.然后,您可以非常快速地检查该集合中是否有任何特定单词.然后,取出每个单词,并检查它的所有前缀是否都存在于有效单词列表中.由于"a"和"I"是英语中的有效单词,您是否会删除以"a"开头的所有有效单词,或者您是否有规则设置前缀的最小长度?
我在我的Ubuntu安装中使用文件/ usr/share/dict/words.这个文件中有各种奇怪的东西; 例如,它似乎包含每个字母本身作为一个单词.因此,"k"在那里,"q","z"等.就我所知,这些都不是单词,但出于某些技术原因它们可能在那里.无论如何,我决定从我的有效单词列表中简单地排除任何短于三个字母的内容.
这是我想出的:
# build valid list from /usr/dict/share/words
wfile = "/usr/dict/share/words"
valid = set(line.strip() for line in open(wfile) if len(line) >= 3)
lst = ["ark", "booze", "kite", "live", "rodeo"]
def subwords(word):
for i in range(len(word) - 1, 0, -1):
w = word[:i]
yield w
newlst = []
for word in lst:
# uncomment these for debugging to make sure it works
# print "subwords", [w for w in subwords(word)]
# print "valid subwords", [w for w in subwords(word) if w in valid]
if not any(w in valid for w in subwords(word)):
newlst.append(word)
print(newlst)
Run Code Online (Sandbox Code Playgroud)
如果你是单行的粉丝,你可以取消for列表并使用列表理解:
newlst = [word for word in lst if not any(w in valid for w in subwords(word))]
Run Code Online (Sandbox Code Playgroud)
我认为这比它应该更简洁,我喜欢能够输入print语句进行调试.
嗯,来想一想,如果你只是添加另一个功能,它不是太简洁:
def keep(word):
return not any(w in valid for w in subwords(word))
newlst = [word for word in lst if keep(word)]
Run Code Online (Sandbox Code Playgroud)
如果你创建这样的函数,Python可以很容易阅读和理解,并给它们好名字.
我假设您只有一个列表,您要从中删除在同一列表中具有前缀的任何元素.
#Important assumption here... wordlist is sorted
base=wordlist[0] #consider the first word in the list
for word in wordlist: #loop through the entire list checking if
if not word.startswith(base): # the word we're considering starts with the base
print base #If not... we have a new base, print the current
base=word # one and move to this new one
#else word starts with base
#don't output word, and go on to the next item in the list
print base #finish by printing the last base
Run Code Online (Sandbox Code Playgroud)
编辑:添加了一些注释,使逻辑更明显