2014-09-01 47 views
-1

我有一個腳本用於從最大模糊比率中找到最佳文件。所選文件將被使用。但我得到這個錯誤:python NameError從最大模糊值文件中選擇

with open(best_fuzzy_file,'r') as file: 
NameError: name 'best_fuzzy_file' is not defined 
>>> 

請幫我解決我的代碼! 我的代碼:

for j in cursor.fetchall(): 
    s1=j[0] 

    def good_ratio(a): 
     return fuzz.token_set_ratio(a, s1) 
    for dir_entry in os.listdir(path): 
     dir_entry_path = os.path.join(path, dir_entry) 
     if os.path.isfile(dir_entry_path): 

      condition_matched_in_file = False 
      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 
       fuzzinessav=(my_sum/my_len) 
       filenames2fuzz[dir_entry_path].append(fuzzinessav) 
      best_fuzziness_ratio = 0 
      for k, v in filenames2fuzz.items():      
        if max(v) > best_fuzziness_ratio: 
         best_fuzzy_file = k       
         best_fuzziness_ratio = max(v) 
    with open(best_fuzzy_file) as f: #<-Gets me an error 
       print best_fuzzy_file 
+0

「best_fuzzy_file」應該被定義爲默認值例如,在第一個循環中爲空字符串,並在打開文件之前添加預先檢查,無論該文件是否存在。解決您的問題。 – Anvesh 2014-09-01 13:42:28

+0

for循環的條件永遠不會是真的,因此best_fuzzy_file沒有定義。真正的硬編碼默認值 – user590028 2014-09-01 13:43:05

+0

有很多條件下'best_fuzzy_file'永遠不會被分配;沒有數據,就不可能說出哪些是導致你的錯誤。你應該把這段代碼分成幾個單獨的函數,你可以單獨測試每個函數。 – jonrsharpe 2014-09-01 13:43:47

回答

0
import os 
for j in cursor.fetchall(): 
    best_fuzzy_file = '' 
    s1=j[0] 

    def good_ratio(a): 
     return fuzz.token_set_ratio(a, s1) 
    for dir_entry in os.listdir(path): 
     dir_entry_path = os.path.join(path, dir_entry) 
     if os.path.isfile(dir_entry_path): 

      condition_matched_in_file = False 
      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 
       fuzzinessav=(my_sum/my_len) 
       filenames2fuzz[dir_entry_path].append(fuzzinessav) 
      best_fuzziness_ratio = 0 
      for k, v in filenames2fuzz.items():      
        if max(v) > best_fuzziness_ratio: 
         best_fuzzy_file = k       
         best_fuzziness_ratio = max(v) 
    if os.path.exists(file_location+'/'+best_fuzzy_file): # can be checked using other modules 
     with open(best_fuzzy_file) as f: 
      print best_fuzzy_file 

我在for循環開始時所定義的「best_fuzzy_file」和prechecked使用os模塊的文件..

+0

感謝您的解決,它的效果很好! – 2014-09-01 14:59:03