繁体   English   中英

Python中的模糊URL匹配

[英]Fuzzy URL matching in Python

我想找到一种可以很好地处理模糊匹配URL的工具,这些URL相同,但需要额外的参数。 例如,对于我的用例,这两个URL是相同的:

atest = (http://www.npr.org/templates/story/story.php?storyId=4231170', 'http://www.npr.org/templates/story/story.php?storyId=4231170&sc=fb&cc=fp)

乍一看, fuzz.partial_ratiofuzz.token_set_ratio Fuzzywuzzy会以100个阈值完成工作:

ratio = fuzz.ratio(atest[0], atest[1])
partialratio = fuzz.partial_ratio(atest[0], atest[1])
sortratio = fuzz.token_sort_ratio(atest[0], atest[1])
setratio = fuzz.token_set_ratio(atest[0], atest[1])
print('ratio: %s' % (ratio))
print('partialratio: %s' % (partialratio))
print('sortratio: %s' % (sortratio))
print('setratio: %s' % (setratio))
>>>ratio: 83
>>>partialratio: 100
>>>sortratio: 83
>>>setratio: 100

但是此方法失败,在其他情况下返回100,例如:

atest('yahoo.com','http://finance.yahoo.com/news/earnings-preview-monsanto-report-2q-174000816.html')

我的数据中的URL和添加的参数相差很大。 我想知道是否有人使用URL解析或类似方法有更好的方法?

如果您只需要检查第二个URL中是否存在第一个URL中的所有查询参数,则可以通过设置差异来以一种更简单的方式进行操作:

import urllib.parse as urlparse

base_url = 'http://www.npr.org/templates/story/story.php?storyId=4231170'
check_url = 'http://www.npr.org/templates/story/story.php?storyId=4231170&sc=fb&cc=fp'

base_url_parameters = set(urlparse.parse_qs(urlparse.urlparse(base_url).query).keys())
check_url_parameters = set(urlparse.parse_qs(urlparse.urlparse(check_url).query).keys())

print(base_url_parameters - check_url_parameters)

这将返回一个空集,但是如果您将基本网址更改为类似

base_url = 'http://www.npr.org/templates/story/story.php?storyId=4231170&test=1'

它将返回{'test'} ,这表示第二个URL中缺少基本URL中的其他参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM