簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM