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

标签 python file-io

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

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

相关文章:

python - 如何满足 Python 中 AWS CDK Lambda 的 CfnFunction "code"参数?

python - MetPy 和 COSMO 的旋转纬度经度网格?

python - Python 中的子类化和内置方法

matlab - 使用 cell2mat 将数字矩阵与字符串向量(列标签)连接起来的问题

ruby - 如何在 ruby​​ 中的特定行开始读取大文件

python - [ orth , pos , tag , lema 和 text ] 的 spaCy 文档

python - 列表依赖性问题(python)

bash - UNIX:如何以文件作为输入来运行程序

regex - 查找多行 block

c - 如何将 .txt 文件的内容复制到 char 数组中?