【发布时间】:2019-12-16 06:11:35
【问题描述】:
在 Python 3.6.5 中,假设我有一个字符串,从文件中读取,如下所示:
# comments
newmtl material_0_2_8
Kd 1 1 1
Ka 0 0 0
Ks 0.4 0.4 0.4
Ke 0 0 0
Ns 10
illum 2
map_Kd ../images/texture0.png
newmtl material_1_24
Kd 1 1 1
Ka 0 0 0
Ks 0.4 0.4 0.4
Ke 0 0 0
Ns 10
illum 2
newmtl material_20_1_8
Kd 1 1 1
Ka 0 0 0
Ks 0.4 0.4 0.4
Ke 0 0 0
Ns 10
illum 2
d 1.0
map_Kd ../images/texture0.jpg
... and so on ...
我在循环每个纹理,需要获取对应的材质代码。
我想检索与某个texture*对应的子字符串material_*,我知道它的名字。
例如,如果我有texture0.jpg,我想返回material_20_1_8;如果我有texture0.png,那么我想要material_0_2_8。
我该怎么做?
f=open('path/to/file', "r")
if f.mode == 'r':
contents =f.read() # contains the string shown above
for texture in textures: # textures is the list of the texture names
material_code = ?
或任何其他方式,如果您认为自己知道更好的方式。
【问题讨论】:
-
只返回第一行,以防最后一行对应每个块的某个文件
-
我认为最好做一个预处理阶段,在这个阶段你解析每个段落并将结果保存为,比如说,一个字典。从那里检索数据将是微不足道的
material_code = materials[texture] -
@AlexandreB。是的,已编辑。
-
@BlueRineS 如何划分块?
-
@Tomerikoo 我想避免更改原始文件或创建新文件
标签: python python-3.x string substring