首页 > 解决方案 > 动态调用python方法

问题描述

我想循环遍历所有模糊匹配方法,以确定哪种方法最适合我的数据,来自模糊伍兹包。

代码:

from fuzzywuzzy import fuzz

# Discover ratio.
# This set should give a higher match than the set below.
high_match = ('AMERICAN SIGN LANG & ENG SECONDAR',
                   '47 The American Sign Language and English Secondary School')

low_match = ('AMERICAN SIGN LANG & ENG SECONDAR',
                   'The 47 American Sign Language & English Lower School')

method_list = [func for func in dir(fuzz) if callable(getattr(fuzz, func))]

for method in method_list:

    high_ratio = fuzz.method(*high_match)

    low_ratio = fuzz.method(*low_match)

    def success(high_ratio, low_ratio):
        if high_ratio > low_ratio:
            return 'success'
        else:
            return 'failure'

    print(f'The method {method} produced {success(high_ratio,low_ratio)}')

fuzz.method是无效的。

我看了其他答案,但不明白。

标签: pythonnlpfuzzywuzzy

解决方案


method_list 存储的是方法名称列表,而不是实际方法。在调用它们时添加 getattr 方法。

for method in method_list:
    high_ratio = getattr(fuzz,method)(*high_match)

    low_ratio =  getattr(fuzz,method)(*low_match)

您的成功功能仍然存在问题。high_ratio 和 low_ratio 不可比较,因为它们是 SequenceMatchers。你需要先从每个人那里得到分数。


推荐阅读