简体   繁体   中英

How can I read a text file and replace numbers?

If I have many of these in a text file;

<Vertex> 0 {
  -0.597976 -6.85293 8.10038
  <UV> { 0.898721 0.149503 }
  <RGBA> { 0.92549 0.92549 0.92549 1 }
}

...

<Vertex> 1507 {
  12 -5.3146 -0.000708352
  <UV> { 5.7487 0.180395 }
  <RGBA> { 0.815686 0.815686 0.815686 1 }
}

How can I read through the text file and add 25 to the first number in the second row? ( -0.597976 in Vertex 0 )

I have tried splitting the second line's text at each space with .split(' ') , then using float() on the third element, and adding 25, but I don't know how to implicitly select the line in the text file.

The hard way is to use Python Lex/Yacc tools. The hardest (did you expect "easy"?) way is to make a custom function recognizing tokens (tokens would be <Vertex>, numbers, bracers, <UV> and <RGBA>; token separators would be spaces).

I'm sorry but what you're asking is a mini language if you cannot guarantee the entries respect the CR and LFs.

Another ugly (and even harder!) way is, since you don't use recursion in that mini language, using regex. But the regex solution would be long and ugly in the same way and amount (trust me: really long one).

Try using this library: Python Lex/Yacc since what you need is to parse a language, and even when regex is possible to use here, you'll end with an ugly and unmaintainable one. YOU HAVE TO LEARN THE TIPS of language parsing to use this. Have a look Here

If the verticies will always be on the line after , you can look for that as a marker, then read the next line. If you read the second line, .strip() leading and trailing whitespace, then .split() by the space character, you will have a list of your three verticies, like so (assuming you have read the line into a string varaible line :

>>> line = line.strip()
>>> verticies = line.split(' ')
>>> verticies 
    ['-0.597976', '-6.85293', '8.10038']

What now? Call float() on the first item in your list, then add 25 to the result.

The real challenge here is finding the <Vertex> marker and reading the subsequent line. This looks like a homework assignment, so I'll let you puzzle that out a bit first!

If your file is well-formatted, then you should be able to parse through the file pretty easily. Assuming <Vertex> is always on a line proceeding a line with just the three numbers, you could do this:

newFile = []
while file:
    line = file.readline()
    newFile.append(line)
    if '<Vertex>' in line:
        line = file.readline()
        entries = line.strip().split()
        entries[0] = str(25+float(entries[0]))
        line = '  ' + ' '.join(entries)
        newFile.append(line)

with open(newFileName, 'w') as fileToWrite:
    fileToWrite.writelines(newFile)

Try to ignore the lines that start with "<", for example:

L=["<Vertex> 0 {",
   "-0.597976 -6.85293 8.10038",
   "<UV> { 0.898721 0.149503 }",
   "<RGBA> { 0.92549 0.92549 0.92549 1 }"
   ]

for l in L:
    if not l.startswith("<"):
        print l.split(' ')[0]

Or if you read your data from a file:

f = open("test.txt", "r")

for line in f:
    line = line.strip().split(' ')
    try:
        print float(line[0]) +  25
    except:
        pass

f.close()

This syntax looks like a Panda3d .egg file .

I suggest you use Panda's file load, modify, and save functions to work on the file safely; see https://www.panda3d.org/manual/index.php/Modifying_existing_geometry_data

Something like:

INPUT = "path/to/myfile.egg"

def processGeomNode(node):
    # something using modifyVertexData()

def main():
    model = loader.loadModel(INPUT)

    for nodePath in model.findAllMatches('**/+GeomNode').asList():
        processGeomNode(nodePath.node())

if __name__=="__main__":
    main()

It is a Panda3D .egg file. The easiest and most reliable way to modify data in it is by using Panda3D's EggData API to parse the .egg file, modify the desired value through these structures, and write it out again, without loss of data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM