【问题标题】:search and replace text inline in file in Python在 Python 中搜索和替换文件中的内联文本
【发布时间】:2010-08-20 03:25:01
【问题描述】:

我正在尝试将包含传统格式 IP 地址的文件转换为包含二进制格式 IP 地址的文件。

文件内容如下。

src-ip{ 192.168.64.54 }
dst-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() 部分似乎无法正常工作。 .replace 行的第一个参数工作正常。(即将 IP 地址转换为二进制格式) 但是 line.replace 似乎不起作用。感谢您提供任何有关为什么会发生这种情况的帮助或线索。

【问题讨论】:

    标签: python regex replace


    【解决方案1】:
    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)
    

    【讨论】:

      【解决方案2】:

      为什么不改用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
      

      【讨论】:

        【解决方案3】:

        你的代码很奇怪:

        line = line.replace(
            (' '.join([bin(256 + int(x))[3:] for x in '123.123.123.123'.split('.')])),
            bytePattern
            )
        

        第一个参数是一个常量,计算结果为'01111011 01111011 01111011 01111011',bytePattern 是正则表达式 "([01]?\d\d?|2[0-4]\d|25[0-5 ])”,所以实际上是这样的:

        line = line.replace('01111011 01111011 01111011 01111011', "([01]?\d\d?|2[0-4]\d|25[0-5])")
        

        如果您的文件中没有 01111011 01111011 01111011 01111011,这将不起作用。

        .replace() 方法只替换文字字符串,而不是正则表达式。

        【讨论】:

        • 他想把原来的格式转换成二进制地址的文件。
        【解决方案4】:

        如果有任何帮助,这里是我来自 DaniWed IP number conversion between dotnumber string and integer 的旧代码,并添加了一些错误检查。

        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)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-16
          • 1970-01-01
          • 1970-01-01
          • 2016-09-22
          • 2013-06-13
          相关资源
          最近更新 更多