使用 Python 从文件中提取 IP 地址

让我们看看如何使用 Python 从文件中提取 IP 地址。
 

算法 :  

  • 为正则表达式导入 re 模块。
  • 使用 open() 函数打开文件。
  • 读取文件中的所有行并将它们存储在列表中。
  • 声明 IP 地址的模式。正则表达式模式是: 
     
r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
  • 对于列表中的每个元素,使用 search() 函数搜索模式,将 IP 地址存储在列表中。
  • 显示包含 IP 地址的列表。

要处理的文件是 test.txt : 
 

test.txt

 

  • 代码
# importing the module
import re

# opening and reading the file
with open('f:/test.txt', encoding='utf-8') as fh:
    fstring = fh.readlines()

# declaring the regex pattern for IP addresses
pattern = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')

# initializing the list object
lst = []

# extracting the IP addresses
for line in fstring:
    match = pattern.search(line)
    if match is not None:
        lst.append(match[0])
    else:
        lst.append(None)

# displaying the extracted IP addresses
print(lst)

输出 :

上面的 Python 程序显示文件中存在的任何类型的 IP 地址。我们还可以显示有效的IP 地址。

有效 IP 地址的规则: 

  • 数字应在 0-255 范围内
  • 它应该由 4 个以“.”分隔的单元格组成。

有效 IP 地址的正则表达式是:
 

((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5] |2[0-4][0-9]|[01]?[0-9][0-9]?)

 

用于有效 IP 的正则表达式说明:

由于我们不能在正则表达式中使用 0-255 范围,我们将其分为 3 组:

  • 25[0-5] - 表示从 250 到 255 的数字
  • 2[0-4][0-9] – 表示从 200 到 249 的数字
  • [01]?[0-9][0-9]?- 表示从 0 到 199 的数字

要处理的文件是 test2.txt : 

000.0000.00.00
192.168.1.1
912.465.123.123
192.168.4.164
69.168.4.226
32.89.31.164
67.168.3.227

 代码:

# importing the module
import re

# opening and reading the file
with open('test2.txt', encoding='utf-8') as fh:
    string = fh.readlines()

# declaring the regex pattern for IP addresses
pattern = re.compile('''((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)''')

# initializing the list objects
valid = []
invalid = []

# extracting the IP addresses
for line in string:
    line = line.rstrip()
    result = pattern.search(line)

    # valid IP addresses
    if result:
        valid.append(line)

    # invalid IP addresses
    else:
        invalid.append(line)

# displaying the IP addresses
print("Valid IPs")
print(valid)
print("Invalid IPs")
print(invalid)

输出 :

"C:\Program Files\Python39\python.exe" C:/Users/Administrator/PycharmProjects/pythonProject8/ExtractIP2.py
Valid IPs
['192.168.1.1', '192.168.4.164', '69.168.4.226', '32.89.31.164', '67.168.3.227']
Invalid IPs
['000.0000.00.00', '912.465.123.123']

进程已结束,退出代码为 0


 

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值