简体   繁体   English

如何阅读文本文件并替换数字?

[英]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? 如何阅读文本文件,并在第二行的第一个数字中加上25? ( -0.597976 in Vertex 0 ) Vertex 0 -0.597976

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. 我尝试使用.split(' ')在每个空格处分割第二行的文本,然后在第三个元素上使用float()并添加25,但是我不知道如何在文本文件中隐式选择该行。

The hard way is to use Python Lex/Yacc tools. 困难的方法是使用Python Lex / Yacc工具。 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). 最困难的方法(您是否期望“简单”吗?)是使自定义函数识别令牌(令牌为<Vertex>,数字,括号,<UV>和<RGBA>;令牌分隔符为空格)。

I'm sorry but what you're asking is a mini language if you cannot guarantee the entries respect the CR and LFs. 很抱歉,如果您不能保证条目尊重CR和LF,那么您要问的是一种迷你语言。

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. 尝试使用该库: Python Lex / Yacc,因为您需要的是解析一种语言,即使在这里可以使用正则表达式,您也将以一个丑陋且难以维护的结尾。 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 : 如果您读第二行, .strip()和结尾的空格,然后阅读.split().strip()空格字符,则将获得三个顶点的列表,如下所示(假设您已将该行读入字符串可变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. 在列表中的第一项上调用float() ,然后将25加到结果中。

The real challenge here is finding the <Vertex> marker and reading the subsequent line. 这里真正的挑战是找到<Vertex>标记并读取下一行。 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: 假设<Vertex>始终在一行上,而只有三个数字在一行上,则可以执行以下操作:

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 . 该语法看起来像是Panda3d .egg文件

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 参见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. 这是一个Panda3D .egg文件。 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. 修改数据的最简单,最可靠的方法是使用Panda3D的EggData API解析.egg文件,通过这些结构修改所需的值,然后再次将其写出,而不会丢失数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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