python模糊reduce()没有初始值

时间:2014-07-12 16:54:07

标签: python

我正在尝试一个程序来查找目录中所有文本文件行中 good 这个词的平均模糊比率,我得到以下异常:

Traceback (most recent call last):
  File "C:/Python27/hukj.py", line 28, in <module>
    my_sum, my_len = reduce(lambda a, b: (a[0]+b[0], a[1]+b[1]), ((good_ratio(i), 1) for i in my_file))
TypeError: reduce() of empty sequence with no initial value

以下程序:

import os
path = r'C:\Python27' 
data = {}
from fuzzywuzzy import fuzz

def good_ratio(a):
   return fuzz.ratio(a, 'good')

for dir_entry in os.listdir(path):
        dir_entry_path = os.path.join(path, dir_entry)
        if os.path.isfile(dir_entry_path):
            with open(dir_entry_path, 'r') as my_file:
               my_sum, my_len = reduce(lambda a, b: (a[0]+b[0], a[1]+b[1]), ((good_ratio(i), 1) for i in my_file))
               print(my_sum/my_len)

什么可能导致此异常?

1 个答案:

答案 0 :(得分:3)

这意味着((good_ratio(i), 1) for i in my_file)生成器表达式没有产生任何值:

>>> reduce(lambda a, b: None, ())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: reduce() of empty sequence with no initial value

仅当您的dir_entry_path文件为空时才会发生这种情况;例如根本没有生产线。

您可以简单地捕获异常并转到下一个文件:

with open(dir_entry_path, 'r') as my_file:
   try:
       my_sum, my_len = reduce(lambda a, b: (a[0]+b[0], a[1]+b[1]), ((good_ratio(i), 1) for i in my_file))
   except TypeError:
       # file empty, move to next file
       continue
   print(my_sum/my_len)