使用python处理和替换第一字符串并维护第二字符串行

时间:2019-03-19 07:16:43

标签: python string text

我有一个文件(sysid.txt),其中包含多行数据(系统ID和主机名),如下所示:

0192.4500.0000 uue01.re1                              
0192.4500.0010 ccu01.re1                              
0192.4500.0110 uue02.re1                               
0192.4500.0001 core1.re2                                   

根据此处的信息和帮助,当我运行下面的代码时,第一个字符串(数字)已成功按需替换,但第二个字符串(主机名)丢失,并且输出以单行显示。

file1 = open('sysid.txt', 'r')
file2 = open('sysip.txt', 'w')
file1_cont = file1.readlines()
for line in file1_cont:
    line = line.replace('.', '')
    f = itemgetter(slice(0,3), slice(3,6), slice(6,9), slice(9,12))
    line = '.'.join(f(line.replace('.','')))
    line = '{}.{}.{}.{}'.format(*map(int, f(line.replace('.', ''))))
    file2.write(line)
    print(line)

sysip.txt的输出

10.89.0.010.89.0.110.89.0.3210.89.0.3310.89.0.3410.89.0.3510.89.0.64

阅读每一行,我想替换第一个字符串(数字)并维护第二个字符串(主机名),如下所示

192.45.0.0 uue01.re1                              
192.45.0.10 ccu01.re1                              
192.45.0.110 uue02.re1                               
192.45.0.1 core1.re2

我该如何处理第一个字符串/数字并将输出行(file2.write(line))保存在新行中,并同时保留上述第二个字符串。

感谢您的支持和指导。

更新后的list.txt ...

System ID      Hostname                                        
0192.4500.0000 uue01.re1                              
0192.4500.0010 ccu01.re1                              
0192.4500.0110 uue02.re1                               
0192.4500.0001 core1.re2 

{master}

2 个答案:

答案 0 :(得分:0)

  

我该如何操纵第一字符串/数字[...]并同时保留上述第二字符串。

似乎您可以在替换点之前在空格字符上分割字符串,仅修改所需的部分。

示例:

s = "0192.4500.0010 ccu01.re1                              "
numbers, host = s.split()
numbers = numbers.replace(".", "")
# TODO: fill in appropriate conversions with `numbers` here
print(numbers, host)

输出为:

019245000010 ccu01.re1

供参考:


  

我如何在新行中保存输出行(file2.write(line))

将输出写入文件时,不会自动添加换行符。您需要自己将它们添加到字符串中。

示例:

numbers = "{}.{}.{}.{}".format(*numbers)
line = "{} {}\n".format(numbers, host)
outf.write(line)

此外,使用with语句打开并最终关闭文件也是一种好习惯。

供参考:

答案 1 :(得分:0)

list.txt:

0192.4500.0000 uue01.re1                              
0192.4500.0010 ccu01.re1                              
0192.4500.0110 uue02.re1                               
0192.4500.0001 core1.re2   

因此

def removeZeros(ip):
    # splits the ip by "."
    # converts the words to integeres to remove leading removeZeros
    # convert back the integer to string and join them back to a string
    new_ip = ".".join([str(int(i)) for i in ip.split(".")])
    return new_ip

logFile = "list.txt"
with open(logFile) as f:
    content = f.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]

for line in content:
    line = line[1:].split(" ")[0]
    line =  removeZeros(line).replace(removeZeros(line).split(".", 2)[1],removeZeros(line).split(".", 2)[1][:-2] + ".0")
    print(line)

输出

192.45.0.0
192.45.0.10 
192.45.0.110 
192.45.0.1 

编辑

如果要将新的IP list覆盖到同一个文件,则可以创建两个单独的列表来存储ipstext

logFile = "list.txt"
with open(logFile) as f:
    content = f.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]
ipList = []
stList = []
for line in content:
    stList.append(line[1:].split(" ")[1])
    line = line[1:].split(" ")[0]
    line =  removeZeros(line).replace(removeZeros(line).split(".", 2)[1],removeZeros(line).split(".", 2)[1][:-2] + ".0")
    ipList.append(line)
    # print(line)

with open(logFile, "w") as f:
    for index in range(len(ipList)):
        f.write(str(ipList[index]) + " " + str(stList[index]) + "\n")

输出(来自文件)

192.45.0.0 uue01.re1
192.45.0.10 ccu01.re1
192.45.0.110 uue02.re1
192.45.0.1 core1.re2

编辑3

要删除第一行和最后一行,请使用切片:

替换此行:

for line in content:

与此:

for line in content[1:-1]:  # after the first and before the last line