У меня есть несколько .log
файлов, которые выглядят следующим образом:
#Software: Microsoft Internet Information Services 10.0
#Version: 1.0
#Date: 2020-04-02 00:09:16
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
2020-04-02 00:14:16 172.31.11.70 GET /ben_laptop_Apple.html - 443 - 156.154.81.54 curl/7.54.0 - 404 0 2 28
...
2020-04-02 00:19:16 172.31.11.70 GET /ben_laptop_Apple.html - 443 - 123.123.23.23 curl/7.54.0 - 404 0 2 47
Я хочу проанализировать и объединить поля, чтобы получить красиво отформатированную таблицу Pandas. Для этого у меня хорошо работает следующее:
# Match the extension pattern and save the list of file names in the ‘all_filenames’ variable.
extension = 'log'
all_filenames = [i for i in glob.glob('*.{}'.format(extension))]
# Use pandas to concatenate all files in the list and export as CSV. The output file is named “combined_csv.csv” located in your working directory.
fields = 'date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken'.split(' ')
#combine all files in the list
combined_csv = pd.concat([pd.read_csv(f, sep=' ', header=None, skiprows=4, names=fields) for f in all_filenames ])
Как видите, я пропускаю первые 4 строки, чтобы удалить текст заголовка. Однако проблема в том, что один файл журнала будет иметь текст заголовка, повторенный по всему файлу .log
. Таким образом, мои файлы на самом деле выглядят так:
#Software: Microsoft Internet Information Services 10.0
#Version: 1.0
#Date: 2020-04-02 00:09:16
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
2020-04-02 00:14:16 172.31.11.70 GET /ben_laptop_Apple.html - 443 - 156.154.81.54 curl/7.54.0 - 404 0 2 28
...
#Software: Microsoft Internet Information Services 10.0
#Version: 1.0
#Date: 2020-04-02 00:09:16
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
...
2020-04-02 00:19:16 172.31.11.70 GET /ben_laptop_Apple.html - 443 - 123.123.23.23 curl/7.54.0 - 404 0 2 47
Как отфильтровать повторяющийся текст заголовка? Я предполагаю, что мне нужно решение RegEx.