[Tutor PyCZ] najdi, nahrad, uloz v ascii subore

b b borique na gmail.com
Středa Srpen 23 12:19:24 CEST 2006


Zdravim,

potreboval by som poradit.

Priklad (jeden blok v subore):
$------------------------
NAME='ALFA'
CODE='x'
$------------------------

Takychto blokov je v subore vela s roznymi menami a kodmi. Potrebujem
naprogramovat skript ktory prehlada cely subor a najde vyrazy s menami
ALFA a podla toho co za kazdou ALFOU bude nasledovat (napr. x,y,z)
zmeni meno ALFA na BETAx,BETAy, BETAz a zemeneny subor ulozi.

Dostal som sa k tomu ze najdem vsetky vyrazy ktore potrebujem, podla
kodu zmenim meno na BETAx,y alebo z ale uz neviem ako zapisat nove
nazvy na rovnake miesto ako bola dana ALFA. Vzdy mi to zapise na
koniec suboru. Tu je moj kod.
Dakujem vopred za akukolvek pomoc.

 import shutil

NamFile="test2.nam"
BackupNamFile = 1
if BackupNamFile == 1:
     shutil.copyfile(NamFile,NamFile.replace(".nam",".nam.bak"))
LineNum=1
LineNumQuantity=0
ArrayCount=0
LineNumArray=[]
ReqArray=[]
ReqName=""
NamFileOpen=file(NamFile,"r+")
for line in NamFileOpen:
     LineTextFound1 = line.find("bk")
     LineTextFound2 = line.find("_results")
     if LineTextFound1 != -1 and LineTextFound2 != -1:
          ReqName=line.split("'")[1]
          print "Line: \t\t\t"+ str(LineNum)
          print "Request Name: \t\t"+ ReqName
          LineNumQuantity = LineNum + 2
          ReqArray=[LineNum-2,ReqName]
     if LineNum == LineNumQuantity:
          QuantityName=line.split("'")[1]
          print "Quantity Type: \t\t"+QuantityName
          if QuantityName == "dx":
               Suffix = "_disp"
          elif QuantityName == "vx":
              Suffix = "_velo"
          elif QuantityName == "fx":
               Suffix = "_force"
          else:
               Suffix = "_results"
          print "Suffix: \t\t"+Suffix
          NewReqName=ReqName.replace("_results",Suffix,1)
          ReqArray.append(NewReqName)
          LineNumArray.insert(ArrayCount,ReqArray)
          ArrayCount+=1
          print "New Request Name: \t"+NewReqName
          print "-----------------------"
     LineNum = LineNum+1
print LineNumArray
print len(LineNumArray)
NamFileOpen.close()

NamFileOpen2=file(NamFile,"r+")
LineNum=1
for i in LineNumArray:
     print i
     for line in NamFileOpen2:
          print line
          print LineNum
          print i[1]
          if i[0]== LineNum:
               print i[0]
               print LineNum
               print line
               Temp=line.replace(line.split("'")[1],i[2],1)
               print Temp
               NamFileOpen2.write(Temp)
          LineNum=LineNum+1
NamFileOpen2.close()


Další informace o konferenci Tutor