gpt4 book ai didi

python - 在python中读取混合字符串和数字的文件数据

转载 作者:太空宇宙 更新时间:2023-11-03 19:36:49 35 4
gpt4 key购买 nike

我想读取一个目录中具有以下结构的不同文件:

#   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/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com