如果我在一个文本文件中有数百个这样的文件;
<Vertex> 0 {
-10.6272 8.71309 10.8633
<UV> { 0.724203 0.210816 }
<RGBA> { 0.916 0.609 0.439 1 }
}如何让Python遍历文本文件并将第二行;-10.6272 8.71309 10.8633;的每个<Vertex>标记放到一个列表中?
发布于 2014-03-29 17:56:47
catch = False
mylist = []
with open("myfile.txt", "r") as f:
content = f.readlines()
for line in content:
if line.startswith("<Vertex>"):
catch = True
continue
if catch:
catch = False
mylist.append(line)这应该能行。
发布于 2014-03-29 18:00:03
您可以使用正则表达式来完成这一任务:
>>> import re
>>> r = re.compile("^<Vertex>\s*\d+\s*{\s*([-\d. ]+)", re.MULTILINE)
>>> with open("filename") as fd:
>>> matches = r.findall(fd.read())
>>> matches
['-10.6272 8.71309 10.8633', '-10.6272 8.71309 10.8633', ...]发布于 2014-03-29 17:58:38
如果您不担心文件的一致性,那么这很容易。
def readFile(path):
f = open(path, 'r')
return f.readlines()
def parseVertexes(lines):
coordinates = []
for index, line in enumerate(lines):
if index % 5 == 1: #second line in vertex
coordinates.append(line.split(" "))我还没做过充分的测试,但这应该是可行的。如果文件不一致,您必须建立更多的基础设施来处理情况。
https://stackoverflow.com/questions/22734578
复制相似问题