在Python中在线搜索和替换文件中的文本

0 投票
4 回答
2935 浏览
提问于 2025-04-16 03:03

我正在尝试把一个包含传统格式IP地址的文件转换成一个包含二进制格式IP地址的文件。

文件的内容如下:

源IP{ 192.168.64.54 }
目标IP{ 192.168.43.87 }


我现在的代码如下:

import re
from decimal import *

filter = open("filter.txt", "r")

output = open("format.txt", "w")

for line in filter:
        bytePattern = "([01]?\d\d?|2[0-4]\d|25[0-5])"
        regObj = re.compile("\.".join([bytePattern]*4))
        for match in regObj.finditer(line):
            m1,m2,m3,m4 = match.groups()
            line = line.replace((' '.join([bin(256 + int(x))[3:] for x in '123.123.123.123'.split('.')])),bytePattern)
            print line

在这段代码中,line.replace() 似乎没有正常工作。它的第一个参数可以正常运行(也就是说,它能把IP地址转换成二进制格式),但是 line.replace 似乎没有效果。希望能得到一些帮助或者线索,看看为什么会这样。

4 个回答

0

如果这对你有帮助的话,这是我之前在DaniWed上写的旧代码,链接是点数字符串和整数之间的IP号码转换,我还加了一些错误检查。

def ipnumber(ip): 
    if ip.count('.') != 3: 
        raise ValueError, 'IP string with wrong number of dots' 
    ip=[int(ipn) for ipn in ip.rstrip().split('.')]
    if any(ipn<0 or ipn>255 for ipn in ip):
        raise ValueError, 'IP part of wrong value: %s' % ip
    ipn=0 
    while ip: 
        ipn=(ipn<<8)+ip.pop(0)
    return ipn 

def ipstring(ip): 
    ips='' 
    for i in range(4): 
        ip,n=divmod(ip,256)
        print n
        if (n<0) or (n>255): 
            raise ValueError, "IP number %i is not valid (%s, %i)." % (ip,ips,n) 
        ips = str(n)+'.'+ips 
    return ips[:-1] ## take out extra point

inp = "src-ip{ 192.168.64.544 } dst-ip{ 192.168.43.87 }"

found=' '
while found:
    _,found,ip = inp.partition('-ip{ ')
    ip,found,inp = ip.partition(' }')
    if ip:
         print ipnumber(ip)
1

为什么不使用 re.sub() 呢?这样可以让你的替换操作更简单,同时也能让你的正则表达式更简洁。

import re
from decimal import *

filter = open("filter.txt", "r")

output = open("format.txt", "w")

pattern = re.compile(r'[\d.]+') # Matches any sequence of digits and .'s

def convert_match_to_binary(match)
    octets = match.group(0).split('.')
    # do something here to convert the octets to a string you want to replace
    # this IP with, and store it in new_form
    return new_form

for line in filter:
    line = pattern.sub(convert_match_to_binary, line)
    print line
2
with open('filter.txt') as filter_:
    with open("format.txt", "w") as format: 
        for line in filter_:
            if line != '\n':
                ip = line.split()
                ip[1] = '.'.join(bin(int(x)+256)[3:] for x in ip[1].split('.'))
                ip[4]= '.'.join(bin(int(x)+256)[3:] for x in ip[4].split('.'))
                ip = " ".join(ip) + '\n'
                format.write(ip)

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

撰写回答