我有一个文本文件,每行都有一个HTTP请求。首先,我从文本文件创建了一个列表,现在尝试计算域发送请求的次数。 每行都有完整的URL,因此我需要删除“.com”之后的任何内容,以仅保留域并计算该域发出的请求总数。例如,根据下面的列表,输出将是
'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']
答案 0 :(得分:1)
您可以使用re
和Counter
-
re.match
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)