简体   繁体   English

使用列表理解在python中读取txt文件

[英]Reading txt file in python using list comprehension

How can I return in python a word which has the same length as a word searched. 如何在python中返回长度与搜索到的单词相同的单词。 For example, I am looking for a closest match for the word "three" in a list of ["three","tea","tree"] and I want to return the first occurence of the same length word. 例如,我正在寻找[“ three”,“ tea”,“ tree”]列表中单词“ three”的最接近匹配,并且我想返回相同长度单词的第一次出现。

I need to do it using generator or some list comprehensions as I have a really big set of data. 我需要使用生成器或一些列表推导来完成此操作,因为我有大量的数据。 Until now I have this function: 到目前为止,我具有以下功能:

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()

Which prints just fine until the 4th or 5th iteration where I get this message error: 直到第四次或第五次迭代出现此错误之前,它的打印效果都很好:

print new_word.next()
StopIteration

Use the next() function and supply a default: 使用next()函数并提供默认值:

new_word = (w for w in matches_list if len(word) == len(w))  
print next(new_word, 'nothing found')

The StopIteration exception is raised because your generator reached the end without a (further) match. 由于您的生成器到达末尾而没有(进一步)匹配,因此引发StopIteration异常。 If you give a second argument to the next() function, then it'll catch that exception and return that second argument as a default instead. 如果将第二个参数提供给next()函数,则它将捕获该异常并将该第二个参数作为默认值返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM