我想读取一个目录中具有以下结构的不同文件:
# Mj = 1.60 ff = 7580.6 gg = 0.8325
我想读取每个文件中的数字并将每个数字与一个向量相关联。 如果我们假设我有 3 个文件,我将有 3 个矢量 Mj 分量,... 我怎样才能用Python做到这一点?
感谢您的帮助。
最佳答案
我会使用正则表达式来分隔该行:
import re
lineRE = re.compile(r'''
\#\s*
Mj\s*=\s*(?P<Mj>[-+0-9eE.]+)\s*
ff\s*=\s*(?P<ff>[-+0-9eE.]+)\s*
gg\s*=\s*(?P<gg>[-+0-9eE.]+)
''', re.VERBOSE)
for filename in filenames:
for line in file(filename, 'r'):
m = lineRE.match(line)
if not m:
continue
Mj = m.group('Mj')
ff = m.group('ff')
gg = m.group('gg')
# Put them in whatever lists you want here.
关于python - 在python中读取混合字符串和数字的文件数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3181460/