alv*_*vas 5 python string pattern-matching string-matching difflib
有没有办法让difflib考虑删除字符串匹配?
我已经尝试了difflib.get_close_matches()但是它不考虑在关闭匹配输出中具有较低长度的字符串.例如
from difflib import get_close_matches as gcm
x = """Erfreulich
Erfreuliche
Erfreulicher
Erfreulicherem
Erfreulicheres
Erfreulicherweis
Erfreulicherweise
Erfreuliches
Erfreulichste"""
x = [i for i in x.split("\n")]
for i in x:
print i, gcm(i,x)
Run Code Online (Sandbox Code Playgroud)
输出:
Erfreulich ['Erfreulich', 'Erfreuliche', 'Erfreuliches']
Erfreuliche ['Erfreuliche', 'Erfreuliches', 'Erfreulicher']
Erfreulicher ['Erfreulicher', 'Erfreuliche', 'Erfreulicheres']
Erfreulicherem ['Erfreulicherem', 'Erfreulicheres', 'Erfreulicher']
Erfreulicheres ['Erfreulicheres', 'Erfreulicherweis', 'Erfreulicherem']
Erfreulicherweis ['Erfreulicherweis', 'Erfreulicherweise', 'Erfreulicheres']
Erfreulicherweise ['Erfreulicherweise', 'Erfreulicherweis', 'Erfreulicheres']
Erfreuliches ['Erfreuliches', 'Erfreuliche', 'Erfreulicheres']
Erfreulichste ['Erfreulichste', 'Erfreuliche', 'Erfreuliches']
Run Code Online (Sandbox Code Playgroud)
请注意,对于字符串Erfreulicher,Erfreulich虽然距离仅为-1,但不会被视为近似匹配.
从文档中,n可以增加参数以获得更多匹配.有些单词较短,所以difflib考虑删除.
difflib.get_close_matches(word,possibilities [,n] [,cutoff])
返回最佳"足够好"的匹配列表.word是需要密切匹配的序列(通常是字符串),并且可能性是与字匹配的序列列表(通常是字符串列表).可选参数n(默认值3)是要返回的最大匹配数; n必须大于0.
可选参数cutoff(默认值为0.6)是[0,1]范围内的浮点数.不会得到至少与单词类似的得分的可能性被忽略.
可能性中的最佳(不超过n)匹配在列表中返回,按相似性得分排序,最相似.
这是同一个词gcm(i,x,6):
Erfreulicher ['Erfreulicher', 'Erfreuliche', 'Erfreulicheres', 'Erfreulicherem',
'Erfreuliches', 'Erfreulich']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1602 次 |
| 最近记录: |