Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从列表中的每个项目中删除字符并计算相同的项目_Python_Count - Fatal编程技术网

Python 从列表中的每个项目中删除字符并计算相同的项目

Python 从列表中的每个项目中删除字符并计算相同的项目,python,count,Python,Count,我有一个文本文件,每行都有一个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'

我有一个文本文件,每行都有一个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']
    

您可以使用
re
计数器
-

  • 使用
    re.match
  • 将表达式传递给
    计数器
    构造函数
  • 请注意,(生成器)理解中的
    re.match
    无法处理错误(如果列表包含无效URL,则可能会发生错误)。在这种情况下,您可以考虑使用循环-< /p>。
    r = []
    for i in my_list:
        try:
            r.append(re.match('.*com', i).group(0))
        except AttributeError:
            pass
    
    c = Counter(r)
    
    print(c)
    Counter({'https:/books.com': 3, 'https:/news.com': 4, 'https:/recipes.com': 4})
    
    r = []
    for i in my_list:
        try:
            r.append(re.match('.*com', i).group(0))
        except AttributeError:
            pass
    
    c = Counter(r)