不使用正则表达式从文本文件中提取IP地址

2024-09-30 04:39:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从文本文件中提取IPv4地址,并将其作为列表保存到新文件中,但是,我无法使用正则表达式解析该文件,而是需要逐个检查字符。不太确定从哪里开始,我发现的每件事似乎都以import re作为第一行

到目前为止,这就是我所拥有的

#Opens and prints wireShark txt file
fileObject = open("wireShark.txt", "r")
data = fileObject.read()
print(data)

#Save IP adresses to new file
with open('wireShark.txt') as fin, open('IPAdressess.txt', 'wt') as fout:
    list(fout.write(line) for line in fin if line.rstrip())


#Opens and prints IPAdressess txt file    
fileObject = open("IPAdressess.txt", "r")
data = fileObject.read()
print(data)

#Close Files
fin.close()
fout.close()

所以我打开这个文件,我已经创建了一个文件,我将把提取的IP放入其中,我只是不知道如何在不使用正则表达式的情况下提取它们

谢谢你的帮助


Tags: and文件txtreaddatalineopenprints
1条回答
网友
1楼 · 发布于 2024-09-30 04:39:52

这里有一个可能的解决办法

函数find_first_digit将索引定位在文本中的下一位(如果有),并返回True。Else返回False

函数get_dotget_num读取一个数字/点,让索引位于数字/点之后的位置,并将数字/点返回为str。如果其中一个函数无法获取数字/点,则引发MissMatch异常

在主循环中,找到一个数字,保存索引,然后尝试获取ip

如果成功,则将其写入输出文件

如果任何被调用的函数引发MissMatch异常,请将当前索引设置为保存的索引加上一,然后重新开始

class MissMatch(Exception):pass

INPUT_FILE_NAME = 'text'
OUTPUT_FILE_NAME = 'ip_list'
                

def find_first_digit():
    
    while True:
        c = input_file.read(1)
        if not c: # EOF found!
            return False
        elif c.isdigit():
            input_file.seek(input_file.tell() - 1)
            return True


def get_num():

    num = input_file.read(1)  # 1st digit
    if not num.isdigit():
        raise MissMatch
    if num != '0':
        for i in range(2):    # 2nd 3th digits
            c = input_file.read(1)
            if c.isdigit():
                num += c
            else:
                input_file.seek(input_file.tell() - 1)
                break
    return num


def get_dot():
    
    if input_file.read(1) == '.':
        return '.'
    else:
        raise MissMatch


with open(INPUT_FILE_NAME) as input_file, open(OUTPUT_FILE_NAME, 'w') as output_file:
    while True:
        ip = ''
        if not find_first_digit():
            break
        saved_position = input_file.tell()
        
        try:
            ip = get_num() + get_dot() \
               + get_num() + get_dot() \
               + get_num() + get_dot() \
               + get_num()
        except MissMatch:
            input_file.seek(saved_position + 1)
        else:
            output_file.write(ip + '\n')

相关问题 更多 >

    热门问题