【问题标题】:How to read numerical data from the comment of a .txt file into numpy如何将 .txt 文件注释中的数字数据读入 numpy
【发布时间】:2017-10-11 14:08:42
【问题描述】:

假设我有一些 .txt 文件作为实验测量的输出:

Date: 160818
double polished Si 300 microns
Power before sample: 62.7uW
Power after sample: 33.0uW
position    y1  y2  power
1.00E-01    1.93E+07    1.17E+06    2.32E-05
2.00E-01    1.92E+07    1.16E+06    2.32E-05
3.00E-01    1.93E+07    1.16E+06    2.32E-05
4.00E-01    1.94E+07    1.16E+06    2.30E-05
5.00E-01    1.94E+07    1.16E+06    2.32E-05
6.00E-01    1.93E+07    1.16E+06    2.32E-05
7.00E-01    1.94E+07    1.16E+06    2.32E-05
8.00E-01    1.94E+07    1.16E+06    2.32E-05
9.00E-01    1.93E+07    1.16E+06    2.32E-05
1.00E+00    1.93E+07    1.16E+06    2.32E-05

我知道如何忽略顶部的 cmets,只使用 np.loadtxt(... ,skiprows=5) 导入数据。但是假设我想导入样本之前/之后的功率值,分别是 62.7 和 33.0,我该怎么做?

谢谢

【问题讨论】:

  • 使用常规的python文件读取和解析。

标签: python numpy text import scipy


【解决方案1】:

您可以像平常一样读取文件。 跳过前 2 行,对第 3 行和第 4 行进行字符串操作

类似

before = rows[0] //first row
before = before[21:-2] 

如果我数数正确会给你数字。如果您希望它们作为数字而不是字符串,则可以

before = float(before)

换句话说,只需在导入行后使用字符串操作。

【讨论】:

    【解决方案2】:

    一种选择是使用正则表达式 (REGEX):

    import re
    

    将每一行文本保存到一个列表中:

    with open ("power.txt", "r") as myfile:
        data=myfile.readlines()
    

    遍历列表以找到匹配的“数字字符串”:

    match = list()
    for i in range(len(data)):
    
        match1 = re.search('[0-9]+[.][0-9]+', data[i]) # REGEX
    
        # Matching numbers are appended
        if match1:
            match.append(match1[0])
    

    然后您可以轻松地遍历新列表以打印出数字:

    for i in range(len(match)):
        print(match[i])
    

    可以看到,这个方法也可以获取表格中的数字。

    【讨论】:

      【解决方案3】:

      这只是为了让斯蒂尔先生的回答更加明确。

      with open('physicist.txt') as f:
          f.readline()
          f.readline()
          print(float(f.readline()[21:-3].strip()))
          print(float(f.readline()[20:-3].strip()))
      

      输出:

      62.7
      33.0
      

      【讨论】:

        猜你喜欢
        • 2015-11-23
        • 1970-01-01
        • 2019-09-09
        • 1970-01-01
        • 1970-01-01
        • 2018-04-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多