【问题标题】:Find addresses using Map and Filter functions - Python使用 Map 和 Filter 函数查找地址 - Python
【发布时间】:2020-04-24 08:49:52
【问题描述】:

我必须在 txt 文件中找到 IPv4 地址。 IPv4地址的格式是“点四边形”,即4个数字(0-255)用点(.)分隔

我知道了,但我的问题是我必须使用 地图和过滤功能

这就是我所拥有的

def buscarIPv4(file):
    for line in file:
        b=[]
        pattern = re.compile('(\s[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)')
        a = pattern.search(line)        
        pos_texto = line.find(line)
        if a is not None:
            b = a.group(1)
            print(b)
    return 

谁能帮我解决这个问题? 我必须使用映射和过滤器在 .txt 文件中查找 IPv4 地址

【问题讨论】:

  • 您能帮助我们先发布您尝试过的内容吗?

标签: python dictionary filter find


【解决方案1】:

“re”显然是更好的选择。

import re

ips = re.findall('(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})',open(file).read())

但是如果你不能使用它,那么你需要将你的文件分解成单词并处理单词。这样的事情应该可以工作:

def is_ip(word):
    ds = word.split('.')
    return len(ds)==4 and all(d.isdigit() for d in ds) and all(0<=int(d)<=255 for d in ds)

ips = list(filter(is_ip,open(file).read().split()))

【讨论】:

    猜你喜欢
    • 2018-06-27
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 2012-08-13
    相关资源
    最近更新 更多