【问题标题】:How to count the number of time a unique URL is open in python?如何计算在 python 中打开唯一 URL 的次数?
【发布时间】:2013-06-08 09:52:34
【问题描述】:

我正在运行一个 Python 代码,它读取 URL 列表并使用 urlopen 单独打开每个 URL。某些 URL 在列表中重复。列表的示例如下:

  • www.example.com/page1
  • www.example.com/page1
  • www.example.com/page2
  • www.example.com/page2
  • www.example.com/page2
  • www.example.com/page3
  • www.example.com/page4
  • www.example.com/page4
  • [...]

我想知道是否有一种方法可以实现一个计数器,该计数器会告诉我代码之前打开了唯一 URL 的次数。我想要一个计数器,它会返回列表中每个 URL 以粗体显示的内容。

  • www.example.com/page1 : 0
  • www.example.com/page1 : 1
  • www.example.com/page2 : 0
  • www.example.com/page2 : 1
  • www.example.com/page2 : 2
  • www.example.com/page3 :0
  • www.example.com/page4 : 0
  • www.example.com/page4 : 1

谢谢!

【问题讨论】:

  • 您可以将每个网址保存到一个列表中,然后将您打开的网址与每个保存的网址进行比较吗?或者这是一个需要数据库的大项目?

标签: python counter urlopen


【解决方案1】:

使用collections.defaultdict() 对象:

from collections import defaultdict

urls = defaultdict(int)

for url in url_source:
    print '{}: {}'.format(url, urls[url])

    # process

    urls[url] += 1

【讨论】:

    【解决方案2】:

    为简单起见,使用ioStringIO

    import io
    fin = io.StringIO("""www.example.com/page1
    www.example.com/page1
    www.example.com/page2
    www.example.com/page2
    www.example.com/page2
    www.example.com/page3
    www.example.com/page4
    www.example.com/page4""")
    

    我们使用collections.Counter

    from collections import Counter
    data = [line.strip() for line in f]
    counts = Counter(data)
    new_data = []
    for line in data[::-1]:
        counts[line] -= 1
        new_data.append((line, counts[line]))
    for line in new_data[::-1]:
        fout.write('{} {:d}\n'.format(*line))
    

    这是结果:

    fout.seek(0)
    print(fout.read())
    
    www.example.com/page1 0
    www.example.com/page1 1
    www.example.com/page2 0
    www.example.com/page2 1
    www.example.com/page2 2
    www.example.com/page3 0
    www.example.com/page4 0
    www.example.com/page4 1
    

    编辑

    适用于大文件的较短版本,因为它一次只需要一行:

    from collections import defaultdict
    counts = defaultdict(int)
    
    for raw_line in fin:
        line = raw_line.strip() 
        fout.write('{} {:d}\n'.format(line, counts[line]))
        counts[line] += 1
    

    【讨论】:

    • Counter() 在这里实际上可能有点矫枉过正。如果 OP 只是在 URL 源上循环,只需使用 defaultdict(int) 实例并在处理 url 时以这种方式计数。
    【解决方案3】:

    我认为你不能那样做。 删除列表中的重复项。

    【讨论】:

    • 这是一个大项目,我不想删除重复项。计数器的值准确地告诉代码该做什么。因此,如果 URL 之前打开了 2 次或 x 次,则代码会执行不同的操作。
    猜你喜欢
    • 2016-11-11
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2021-03-08
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多