【问题标题】:Grouping list of similar urls in pythonpython中相似url的分组列表
【发布时间】:2014-02-28 13:48:19
【问题描述】:

我有大量的网址。有些彼此相似,即它们代表相似的页面集。 例如。

    http://example.com/product/1/
    http://example.com/product/2/
    http://example.com/product/40/
    http://example.com/product/33/

相似。同样

    http://example.com/showitem/apple/
    http://example.com/showitem/banana/
    http://example.com/showitem/grapes/

也类似。所以我需要将它们表示为http://example.com/product/(Integers)/ 其中(Integers) = 1,2,40,33http://example.com/showitem/(strings)/ 其中strings = apple,banana,grapes ...等等。

python 中是否有任何内置函数或库可以从大量混合 url 中找到这些相似的 url?如何更有效地做到这一点?请建议。提前致谢。

【问题讨论】:

  • 你需要用它们做什么?
  • 我需要检测这些类型的 url 列表并将它们从一组不同的 url 中分组。

标签: python url optimization


【解决方案1】:

使用字符串存储 URL 的第一部分,只处理 ID,例如:

In [1]: PRODUCT_URL='http://example.com/product/%(id)s/'

In [2]: _ids = '1 2 40 33'.split() # split string into list of IDs

In [3]: for id in _ids:
   ...:     print PRODUCT_URL % {'id':id}
   ...:     
http://example.com/product/1/
http://example.com/product/2/
http://example.com/product/40/
http://example.com/product/33/

语句print PRODUCT_URL % {'id':id} 使用Python string formatting 根据传递的变量id 格式化产品URL。

更新:

我看到你已经改变了你的问题。您的问题的解决方案是特定领域的,并且取决于您的数据集。有几种方法,有些方法比其他方法更手动。一种这样的方法是获取顶级 URL,即检索域名:

In [7]: _url = 'http://example.com/product/33/' # url we're testing with

In [8]: ('/').join(_url.split('/')[:3]) # get domain
Out[8]: 'http://example.com'

In [9]: ('/').join(_url.split('/')[:4]) # get domain + first URL sub-part
Out[9]: 'http://example.com/product'

上面的[:3][:4] 只是对split('/') 产生的列表进行切片

您可以将结果设置为dict 上的一个键,您可以在每次遇到 URL 部分时对其进行计数。并从那里继续前进。同样,解决方案取决于您的数据。如果它比上面更复杂,那么我建议您按照其他答案的建议查看正则表达式。

【讨论】:

  • 此解决方案假定我们已经知道相似的 url。但这种情况并非如此。我有一长串需要自动检测相似网址的网址
  • @user2789099 针对您更新的问题更新了我的答案
【解决方案2】:

您可以使用正则表达式来处理这种情况。你可以去Python documentation看看这个句柄怎么样。

您还可以看到 Django 如何在其routings system 上实现这一点

【讨论】:

    【解决方案3】:

    我不确定您具体在寻找什么。在我看来,您正在寻找与 URL 匹配的内容。如果这确实是您想要的,那么我建议您使用使用正则表达式构建的东西。一个例子可以在here找到。

    我还建议您查看Django 及其routing system

    【讨论】:

      【解决方案4】:

      不是在 Python 中,但我创建了一个 Ruby 库(和一个随附的应用程序)——

      https://rubygems.org/gems/LinkGrouper

      它适用于所有链接(不需要知道任何模式)。

      【讨论】:

      • 嗨,你在积极维护这个吗? gem install 命令不起作用。可以分享一下你用的算法吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      • 2021-08-18
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      相关资源
      最近更新 更多