Python:在文件中搜索,替换前面的条目
我试图以一种特定的方式修改现有的ASCII数据文件。 我想做的是从数组中找到一个字符串,这是我预先定义的。 如果在文件中找到此字符串,我想更改前面的条目;在这里输入的字符串取决于首先找到的字符串 我有一个文件,其中条目用空格分隔,末尾有尾随空格,可以填充30列。相应的字符串不会出现在第一行中,并且每行的字符串不会超过一个。一个例子如下所示: test01out.txt:Python:在文件中搜索,替换前面的条目,python,replace,Python,Replace,我试图以一种特定的方式修改现有的ASCII数据文件。 我想做的是从数组中找到一个字符串,这是我预先定义的。 如果在文件中找到此字符串,我想更改前面的条目;在这里输入的字符串取决于首先找到的字符串 我有一个文件,其中条目用空格分隔,末尾有尾随空格,可以填充30列。相应的字符串不会出现在第一行中,并且每行的字符串不会超过一个。一个例子如下所示: test01out.txt: a0997 b0998 c0999 a1000 b1001 c1002 a10
a0997 b0998 c0999
a1000 b1001 c1002
a1003 b1004 c1005
a1006 a1000 c1007
a1008 b1009 c1010
b1001 b1011 c1012
a1013 b1014 b1001
a1015 b1016 c1017
文件不必在一行中有三列。一行可能只有两列,但也可能有四列或五列
我目前的尝试如下:
from numpy import *
findlines = open("test01.txt").read().split("\n")
searcharray = array(["a1000","b1001"])
alterarray = array(["this1","this2"])
tempstring_current = ""
fileout = open("test01out.txt", "w")
for i, line in enumerate(findlines):
tempstring_last = tempstring_current
tempstring_current = line.rstrip().split(" "))
if any(x in tempstring_current for x in searcharray): # check if one of the elements is in the current line -> unfortunately this seems to be true for any line checked...
print(i)
print(tempstring_current)
for j, element in enumerate(tempstring_current):
if any(searcharray == tempstring_current):
currentsearchindex = argmax(searcharray == tempstring_current)
currentalterstring = alterarray[currentsearchindex]
if currentsearchindex == 0:
tempstring_last.split(" ")[-1] = currentalterstring
else:
tempstring_current.split(" ")[currentsearchindex - 1] = currentalterstring
tempstring_current.split(" ")[currentsearchindex-1] = "XPRZeugs_towrite" + repr(currentdesignatedspeed)
tempstring_last = tempstring_last.ljust(30)
try:
fileout.write(str(tempstring_last))
fileout.write("\r")
try:
fileout.close()
searcharray和alterarray将有更多的元素,而不是两个。
我已经测试了脚本的任何条件;不幸的是,由于某些原因,任何条件似乎总是得到满足,我不太明白:
from numpy import *
findlines = open("test01.txt").read().split("\n")
searcharray = array(["a1000","b1001"])
alterarray = array(["this1","this2"])
tempstring_current = ""
fileout = open("test01out.txt", "w")
for i, line in enumerate(findlines):
tempstring_last = tempstring_current
tempstring_current = line.rstrip().split(" ")
if any(x in tempstring_current for x in searcharray): # check if one of the elements is in the current line -> unfortunately this seems to be true for any line checked...
print(i)
print(tempstring_current)
我得到文件中每一行的打印行,这是我没有预料到的
编辑/解决方案: 我意识到我在输入测试文件中犯了一个错误: 应该是这样的:
a0997 b0998 c0999
a1000 b1001 c1001
a1003 b1004 c1005
a1006 a1000 c1007
a1008 b1009 c1010
c1002 b1011 c1012
a1013 b1014 c1002
a1015 b1016 c1017
执行此作业的完整代码如下所示:
from numpy import *
findlines = open("test01.txt").read().split("\n")
searcharray = array(["a1000","c1002"])
alterarray = array(["this1","this2"])
tempstring_current = ""
fileout = open("test01out.txt", "w")
for i, line in enumerate(findlines):
tempstring_last = tempstring_current
tempstring_current = line.rstrip().split(" ")
if any([x in tempstring_current for x in searcharray]): # check if one of the elements is in the current line -> unfortunately this seems to be true for any line checked...
# print(i)
# print(tempstring_current)
# print(searcharray)
# print([x in tempstring_current for x in searcharray])
# print(argmax([x in tempstring_current for x in searcharray]))
currentsearchposindex = argmax([x in tempstring_current for x in searcharray]) # welchen Index hat das entsprechende Element im Searcharray?
currentalterstring = alterarray[currentsearchposindex] # was ist der entsprechende Eintrag im Alterarray
for j, currentXPRelement in enumerate(tempstring_current):
if currentXPRelement == searcharray[currentsearchposindex]:
currentsearchindex_intemparray = j
# print(len(tempstring_current))
# print(searcharray[currentsearchposindex])
# print(tempstring_current == searcharray[currentsearchposindex])
# print(searcharray[currentsearchposindex] == tempstring_current)
# print(argmax(tempstring_current == searcharray[currentsearchposindex]))
# currentsearchindex_intemparray = argmax(tempstring_current == searcharray[currentsearchposindex])
if currentsearchindex_intemparray == 0:
tempstring_last[-1] = currentalterstring
else:
tempstring_current[currentsearchindex_intemparray - 1] = currentalterstring
# tempstring_current[currentsearchindex_intemparray-1] = "XPRZeugs_towrite" + repr(currentalterstring)
tempstring_last = str(" ".join(tempstring_last)).ljust(30)
if not i == 0:
try:
fileout.write(str(tempstring_last))
fileout.write("\r")
finally:
None
try:
fileout.write(" ".join(tempstring_current))
fileout.write("\r")
fileout.close()
finally:
None
要修复代码,使其至少无法始终匹配,请更改
if any(x in tempstring_current for x in searcharray):
到
我认为原因是'x in tempstring_current for x in searcharray'表达式返回一个interator函数-any()表示'this value(即迭代器函数引用)不是None,因此它是True',因此结果总是True。更改后的语法从迭代器创建一个列表,然后任何元素都可以按您可能需要的方式工作,即,如果列表中的任何元素为true,则返回true。让我澄清一下,您希望在
searcharray
中搜索项,但数组项不能并排放置在输入文件中,对吗?如果我想更改前面的条目,我会向后浏览文件,从右到左阅读每一行。这将使事情变得更容易…您是否尝试过将any表达式扩展为for循环,以便打印调试它的中间步骤?这样你也可以打印出匹配的x。谢谢,这解决了我的问题。我将在一分钟内发布完整的解决方案。
if any([x in tempstring_current for x in searcharray]):