在Python的文本文件中查找一行接一行的结尾

2024-04-19 05:47:52 发布

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

问题

大家好,

在文本文件中,我需要用另一个字符串替换未知字符串

首先要找到它,我需要在“名称模糊2”之前找到行 由于有许多行以“XPO”开头:

 name Blur2
 xpos 12279             # 12279 is the end of line to find and put in a variable

获取未知字符串的代码:

#string to find:
keyString = ' name Blur2'
f2 = open("output_file.txt", 'w+') 
with open("input_file.txt", 'r+') as f1:
    lines = f1.readlines()
    for i in range(0, len(lines)):
        line = lines[i]
        if keyString in line:
            nextLine = lines[i + 1]       
            print ' nextLine: ',nextLine  #result:  nextLine:   xpos 12279
            number = nextLine.rsplit(' xpos ', 1)[1]
            print ' number: ',number  #result: number:  12279
            #convert string to float:
            newString = '{0}\n'.format(int(number)+ 10)
            print ' newString: ',newString    #result: newString:  12289
            f2.write("".join([nextLine.replace(number, str(newString))]))  #this line isn't working
f1.close()
f2.close()

所以,我完全改变了方法,但最后一行:f2。写。。。没有按预期工作,有人知道为什么吗

再次感谢您的帮助:)


Tags: to字符串nameinnumberlineresultf2
2条回答

正则表达式似乎会有所帮助,https://regex101.com/

正则表达式使用定义模式的语言搜索字符串。我列出了学习模式本身最重要的方法,但有时它比python的原生字符串操作更好

首先描述将要使用的模式,然后实际编译该模式。对于字符串检查,我使用r“”将其定义为原始字符串。这意味着我不必在字符串中转义\字符(例如:printing\将是print('\'),而不是print(r'))

这个正则表达式有几个部分

\s表示空白(如空格、“”等字符)

\n或\r对于换行符和回车符,[^]定义不查找的字符(因此[^\n\r]搜索任何不包含换行符或回车符的字符),则*表示可以有0个或多个指定字符。正则表达式字符串中的$表示行结束前的所有字符

因此,模式搜索“name Blur2”,特别是在其后搜索任意数量的空格和换行符。括号允许这是组1(稍后解释)。第二部分“([^\n\r]*$”)捕获在该行结束之前不是换行符或回车符的任意数量的字符

组占括号,因此“(名称蓝色\n)”是组1,而要替换的行“([^\n\r]*$)是组2。checkre.sub应将整个文本替换为组1 和新字符串,所以它用第一行替换第一行,用新字符串替换第二行

import re
check = r'(name Blur2\s*\n)([^\n\r]*$)'
checkre = re.compile(check, re.MULTILINE)
checkre.sub(\g<1>+newstring, file)

由于要检查多行,因此需要设置re.MULTILINE,如果“\n”不匹配,可以使用[\n\r\z]获取行的任意一端、回车或字符串的绝对端

rioV8的注释是有效的,但您也可以使用“{5}$”,它代表行末尾之前的任意5个字符

应该可以使用

oldstring = checkre.search(filestring).group(1)

我还没有和斯潘玩过,但是

stringmatch = checkre.search(filestring)
oldstring = stringmatch.group(2)
newfilestring = filestring[0:stringmatch.span[0]] + stringmatch.group(1) + newstring + filestring[stringmatch.span[1]]:]

虽然拼接可能不完全正确,但应该非常接近您要查找的内容

最初的计划非常接近。我编辑了一点,对一些错误的地方进行了调整

你最初没有写需要替换的行,我不知道你为什么需要连接东西。直接替换号码似乎有效。Python不允许在for循环中更改i,您需要跳过一行,这样它就不会写入文件,所以我将其更改为while循环。不管怎么说,只要你有任何问题,下面的代码就行了

#string to find:
keyString = ' name Blur2'
f2 = open("output_file.txt", 'w+') 
with open("test.txt", 'r+') as f1:
    lines = f1.readlines()
    i=0
    while i <len(lines):
        line = lines[i]
        if keyString in line:
            f2.write(line)
            nextLine = lines[i + 1]
            #end of necessary 'i' calls, increment i to avoid reprinting writing the replaced line string
            i+=1
            print (' nextLine: ',nextLine  )#result:  nextLine:   xpos 12279
            number = nextLine.rsplit(' xpos ', 1)[1]
            #as was said in a comment, this coula also be number = nextLine[-5:]
            print (' number: ',number  )#result: number:  12279
            #convert string to float:
            newString = '{0}\n'.format(int(number)+ 10)
            print (' newString: ',newString)    #result: newString:  12289
            f2.write(nextLine.replace(number, str(newString)))  #this line isn't working
        else:
            f2.write(line)
        i+=1
f1.close()
f2.close()

相关问题 更多 >