无法将字典传递给 Python 中的函数
Unable to pass dictionary to function in Python
我正在尝试使用模糊匹配将单词与列表索引(存储在 csv 中)进行匹配。我将索引加载到字典中。然后创建一个函数来比较给定的两个字符串。如果匹配的比率大于阈值,则 return 索引和索引字符串。
这是我试过的。
def fuzzy_token_set_matching(index_dict, str_for_comparison):
matching_threshold = 70
#If I try to get dict size here, it's 0
print(len(index_dict))
for index, indexed_string in index_dict.items():
max_ratio = 0
#Compare two string using fuzzy matching
fuzz_matching_ratio = fuzz.token_sort_ratio(indexed string, str_for_comparison)
if fuzz_matching_ratio > max_ratio:
max_ratio = fuzz_matching_ratio
if max_ratio > matching_threshold:
return index_index, title
else:
return None
input_file = 'index.csv'
output_file = 'results.csv'
#Load index list into a dictionary
with open(input_file, mode = 'r') as index_infile:
index_reader = csv.reader(index_infile)
index_dict = {rows[0]:rows[2] for rows in index_reader}
print(fuzz.token_sort_ratio(index_dict, 'test'))
>>> Results return: 0
我得到的结果是 0,尽管我有一个完全匹配,应该给我 100 的匹配率。出于某些原因,我无法将字典传递给函数。
我猜你调用了错误的函数。 fuzz.token_sort_ratio(index_dict, 'test')
不是 fuzzy_token_set_matching(index_dict, str_for_comparison)
。
所以您应该尝试以下方法:
print(fuzzy_token_set_matchin(index_dict, 'test'))
我正在尝试使用模糊匹配将单词与列表索引(存储在 csv 中)进行匹配。我将索引加载到字典中。然后创建一个函数来比较给定的两个字符串。如果匹配的比率大于阈值,则 return 索引和索引字符串。
这是我试过的。
def fuzzy_token_set_matching(index_dict, str_for_comparison):
matching_threshold = 70
#If I try to get dict size here, it's 0
print(len(index_dict))
for index, indexed_string in index_dict.items():
max_ratio = 0
#Compare two string using fuzzy matching
fuzz_matching_ratio = fuzz.token_sort_ratio(indexed string, str_for_comparison)
if fuzz_matching_ratio > max_ratio:
max_ratio = fuzz_matching_ratio
if max_ratio > matching_threshold:
return index_index, title
else:
return None
input_file = 'index.csv'
output_file = 'results.csv'
#Load index list into a dictionary
with open(input_file, mode = 'r') as index_infile:
index_reader = csv.reader(index_infile)
index_dict = {rows[0]:rows[2] for rows in index_reader}
print(fuzz.token_sort_ratio(index_dict, 'test'))
>>> Results return: 0
我得到的结果是 0,尽管我有一个完全匹配,应该给我 100 的匹配率。出于某些原因,我无法将字典传递给函数。
我猜你调用了错误的函数。 fuzz.token_sort_ratio(index_dict, 'test')
不是 fuzzy_token_set_matching(index_dict, str_for_comparison)
。
所以您应该尝试以下方法:
print(fuzzy_token_set_matchin(index_dict, 'test'))