подсчет обращений к базе данных по типу пользователя в python - PullRequest
0 голосов
/ 09 июня 2019

У меня есть файл журнала обратного доступа, который я обработал, чтобы он совпадал с URL-адресом и типом пользователя.Мне нужно посчитать, сколько раз данный URL попадал в каждый из типов пользователей.примерные данные:

http://find.galegroup.com:80/ персонал http://www.transnational -dispute-management.com: 80 / студент https://www.investorstatelawguide.com:443/ адъюнкт-визит https://www.jstor.org:443/ факультет https://bmo.bmiresearch.com:443/ основная библиотека https://heinonline.org:443/ oncampus http://find.galegroup.com:80/ студент

Я думал поместить каждый URL как кортеж со счетчиками для каждого типа пользователя.Когда каждая строка читается, она проверяется на соответствие предыдущим совпадениям - если совпадений нет, то инициируется новый кортеж.Если у него есть совпадение, соответствующий счетчик увеличивается и кортеж восстанавливается.

В конце все кортежи записываются в новый файл.

Проблема в том, что у меня нетПонять, как это реализовать.

Указатели, общие стратегии и ответы очень ценятся!

1 Ответ

0 голосов
/ 09 июня 2019

Если вы хотите выполнить эту задачу с помощью регулярного выражения, мы можем просто определить простое выражение, используя чередование, например:

(galegroup\.com)|(jstor\.org)|(investorstatelawguide\.com)

захватите наши нужные домены, тогда мы просто посчитаем:

Демо

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(galegroup\.com)|(jstor\.org)|(investorstatelawguide\.com)"

test_str = ("http://find.galegroup.com:80/ staff http://www.transnational-dispute-management.com:80/ student https://www.investorstatelawguide.com:443/ AdjunctVisiting https://www.jstor.org:443/ faculty https://bmo.bmiresearch.com:443/ mainlibrary https://heinonline.org:443/ oncampus http://find.galegroup.com:80/ student\n"
    "http://find.galegroup.com:80/ staff http://www.transnational-dispute-management.com:80/ student https://www.investorstatelawguide.com:443/ AdjunctVisiting https://www.jstor.org:443/ faculty https://bmo.bmiresearch.com:443/ mainlibrary https://heinonline.org:443/ oncampus http://find.galegroup.com:80/ student\n"
    "http://find.galegroup.com:80/ staff http://www.transnational-dispute-management.com:80/ student https://www.investorstatelawguide.com:443/ AdjunctVisiting https://www.jstor.org:443/ faculty https://bmo.bmiresearch.com:443/ mainlibrary https://heinonline.org:443/ oncampus http://find.galegroup.com:80/ student")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

RegEx Circuit

jex.im визуализирует регулярные выражения:

enter image description here

...