如何告诉 difflib.get_close_matches() 忽略大小写?我有一本字典,它有一个定义的格式,包括大写。但是,测试字符串可能有全大写或没有大写,它们应该是等价的。但是,结果需要正确大写,所以我不能使用修改过的字典。
import difflib
names = ['Acacia koa A.Gray var. latifolia (Benth.) H.St.John',
'Acacia koa A.Gray var. waianaeensis H.St.John',
'Acacia koaia Hillebr.',
'Acacia kochii W.Fitzg. ex Ewart & Jean White',
'Acacia kochii W.Fitzg.']
s = 'Acacia kochi W.Fitzg.'
# base case: proper capitalisation
print(difflib.get_close_matches(s,names,1,0.9))
# this should be equivalent from the perspective of my program
print(difflib.get_close_matches(s.upper(),names,1,0.9))
# this won't work because of the dictionary formatting
print(difflib.get_close_matches(s.upper().capitalize(),names,1,0.9))
输出:
['Acacia kochii W.Fitzg.']
[]
[]
工作代码:
根据 Hugh Bothwell 的回答,我对代码进行了如下修改以获得一个可行的解决方案(当返回多个结果时它也应该有效):
import difflib
names = ['Acacia koa A.Gray var. latifolia (Benth.) H.St.John',
'Acacia koa A.Gray var. waianaeensis H.St.John',
'Acacia koaia Hillebr.',
'Acacia kochii W.Fitzg. ex Ewart & Jean White',
'Acacia kochii W.Fitzg.']
test = {n.lower():n for n in names}
s1 = 'Acacia kochi W.Fitzg.' # base case
s2 = 'ACACIA KOCHI W.FITZG.' # test case
results = [test[r] for r in difflib.get_close_matches(s1.lower(),test,1,0.9)]
results += [test[r] for r in difflib.get_close_matches(s2.lower(),test,1,0.9)]
print results
输出:
['Acacia kochii W.Fitzg.', 'Acacia kochii W.Fitzg.']