我有一个脚本,用于从最大模糊比率中找到最佳文件。所选文件将进一步使用。但是我得到了这个错误:
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 :(得分: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
我已经定义了&#39; best_fuzzy_file n#39;在for循环的开头,使用os模块预先检查文件..