如何使用pythonregex从服务器日志文件中提取IP地址? [英] How to use python regex to extract IP address from server log files?
本文介绍了如何使用pythonregex从服务器日志文件中提取IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在开始使用python。我有一个服务器日志文件,记录我在一段时间内访问的页面。
如何编写一个Python程序来找出访问次数最多的IP地址? 我必须用字典吗? 我已经这样做了,但我不确定如何使用正则表达式获取IP地址。import re
openFile = open('text.txt', "r")
readLines = openFile.read()
# pat = re.compile("^d{1,3}.d{1,3}.d{1,3}.d{1,3}$")
wordfreq = {}
for word in readLines.split():
if word not in wordfreq:
wordfreq[word] = 1
else:
wordfreq[word] += 1
print(wordfreq)
# wordList = [(v,k) for k,v in wordfreq.items()]
# wordList.sort(reverse=True)
#
# print(wordList)
PS:我不想使用来自PYTHON模块的计数器。我正在想办法用词典来做这件事。
推荐答案
除了拉凯什之前发布的内容之外,还有另一种提取IP地址的方法:
import re
pattern = 'd{1,3}.d{1,3}.d{1,3}.d{1,3}'
finalIP = re.findall(pattern, s)
关于计数器,请参考他的回答。我刚刚发布了一个不同的regex!
这篇关于如何使用pythonregex从服务器日志文件中提取IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文