簡體   English   中英

不使用正則表達式從文本文件中提取 IP 地址

[英]Extract IP addresses from text file without using REGEX

我正在嘗試從文本文件中提取 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 放入的文件,我只是不知道如何在不使用 REGEX 的情況下提取它們。

謝謝您的幫助。

這是一個可能的解決方案。

function find_first_digit , position 文本中下一個數字的索引(如果有)並返回True 否則返回False

函數get_dotget_num讀取一個數字/點,並讓 position 的索引緊跟在數字/點之后,並將數字/點作為str返回。 如果其中一個函數未能獲得數字/點,則會引發MissMatch異常。

在主循環中,找到一個數字,保存索引,然后嘗試得到一個 ip。

如果成功,將其寫入 output 文件。

如果任何被調用的函數引發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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM