[英]Reading txt file in python using list comprehension
如何在python中返回长度与搜索到的单词相同的单词。 例如,我正在寻找[“ three”,“ tea”,“ tree”]列表中单词“ three”的最接近匹配,并且我想返回相同长度单词的第一次出现。
我需要使用生成器或一些列表推导来完成此操作,因为我有大量的数据。 到目前为止,我具有以下功能:
matches_list= dl.get_close_matches(word.lower(),list_of_words)
if matches_list:
new_word= (w for w in matches_list if (len(word)==len(w)))
print new_word.next()
直到第四次或第五次迭代出现此错误之前,它的打印效果都很好:
print new_word.next()
StopIteration
使用next()
函数并提供默认值:
new_word = (w for w in matches_list if len(word) == len(w))
print next(new_word, 'nothing found')
由于您的生成器到达末尾而没有(进一步)匹配,因此引发StopIteration
异常。 如果将第二个参数提供给next()
函数,则它将捕获该异常并将该第二个参数作为默认值返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.