Python 使用正则表达式逐行遍历日志文件,查找IP地址模式。每个IP都需要使用extend方法将每个IP添加到列表IP中
我正在编写一个脚本,并尝试使用regex逐行遍历日志文件以查找IP地址模式,然后使用extend方法将每个IP添加到IP列表中。我相信我已经把所有事情都做好了,直到迭代点,然后尝试打印(ips),正如您在脚本中看到的那样Python 使用正则表达式逐行遍历日志文件,查找IP地址模式。每个IP都需要使用extend方法将每个IP添加到列表IP中,python,regex,Python,Regex,我正在编写一个脚本,并尝试使用regex逐行遍历日志文件以查找IP地址模式,然后使用extend方法将每个IP添加到IP列表中。我相信我已经把所有事情都做好了,直到迭代点,然后尝试打印(ips),正如您在脚本中看到的那样 import urllib.request import json import datetime import os import re import azuremaps 我创建了3个空列表来存储找到的数据 ips
import urllib.request
import json
import datetime
import os
import re
import azuremaps
我创建了3个空列表来存储找到的数据
ips = []
unique_ips = []
toJson = []
我打开的日志文件
file=open('logs/access.log','r')
这可能就是我在尝试使用regex逐行遍历日志文件以获取ip地址,然后使用extend方法将这些地址存储在列表ip中时遇到的问题。希望此代码少于5行
pattern = re.compiler(r'(\d{1,3}\.\d{1,3}\.\d{1,3} \.\d{1,3})')
for line in file:
ips.extend(pattern.search(line)[0])
print(ips)
已填充新列表以删除所有重复项
unique_ips = list(set(ips))
在我继续之前,我需要验证我的列表,但是当我在终端中键入print(ips)时,我在意外标记“ips”附近得到bash:syntax error
#print(ips)
#print(len(ips))
#print(len(unique_ips))
#print(unique_ips)
有什么理由一行一行地做吗 假设access.log文件为:
43.53.250.2
65.66.66.69
noise234.85.98.12something
whatever65.66.66.69
我想你可以试试这个:
import re
with open('logs/access.log', 'r') as file:
file = file.read()
pattern = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
ips = pattern.findall(file)
unique_ips = list(set(ips))
print(unique_ips)
关于代码的注意事项:
- 我认为应该重新编译,而不是重新编译
- 看起来您的正则表达式字符串中有一个额外的空格
- 我认为您可以使用
,因为您试图append
一次用一个元素扩展列表
['234.85.98.12', '65.66.66.69', '43.53.250.2']