【问题标题】:Removing characters from each item in a list and counting the same items从列表中的每个项目中删除字符并计算相同的项目
【发布时间】:2017-11-29 00:30:15
【问题描述】:

我有一个文本文件,其中每一行都有一个 HTTP 请求。首先,我从文本文件创建了一个列表,现在尝试计算域发送请求的次数。 每行都有完整的 URL,因此我需要删除“.com”之后的任何内容,以仅保留域并计算该域发出的请求总数。例如,根据下面的列表,输出将是

  • 'https:/news.com': 4
  • 'https:/recipes.com': 4
  • 'https://books.com': 3

    my_list = ['https:/news.com/main', 'https:/recipes.com/main', 
    'https:/news.com/summary', 'https:/recipes.com/favorites', 
    'https:/news.com/today', 'https:/recipes.com/book', 
    'https:/news.com/register', 'https:/recipes.com/', 
    'https:/books.com/main', 'https:/books.com/favorites', 
    'https:/books.com/sale']
    

【问题讨论】:

    标签: python count


    【解决方案1】:

    您可以使用 reCounter 来做到这一点 -

    1. 使用re.match 提取域
    2. 将表达式传递给Counter 构造函数
    from collections import Counter
    import re
    
    c = Counter(re.match('.*com', i).group(0) for i in my_list)
    

    print(c)
    Counter({'https:/books.com': 3, 'https:/news.com': 4, 'https:/recipes.com': 4})
    

    请注意,(生成器)推导式中的re.match 无法处理错误(如果您的列表包含无效的 URL,则可能会发生这种情况)。在这种情况下,您可以考虑使用循环 -

    r = []
    for i in my_list:
        try:
            r.append(re.match('.*com', i).group(0))
        except AttributeError:
            pass
    
    c = Counter(r)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多