【问题标题】:Python numpy.genfromtxtPython numpy.genfromtxt
【发布时间】:2015-06-26 01:17:02
【问题描述】:

有谁知道,我如何从我尝试使用numpy.genfromtxt 读取的文本文件中跳过括号 我的数据文件格式为

1.466 ((5.68 3.3 45.7)(4.5 6.7 9.5))

【问题讨论】:

    标签: python numpy genfromtxt


    【解决方案1】:

    np.genfromtxt 可以接受迭代器:

    import numpy as np
    import re
    
    with open('data', 'r') as f:
        lines = (line.replace('(',' ').replace(')',' ') for line in f)
        arr = np.genfromtxt(lines)
    print(arr)
    

    产量

    [  1.466   5.68    3.3    45.7     4.5     6.7     9.5  ]
    

    或者,您可以使用(在 Python2 中)str.translate 或(在 Python3 中)bytes.translate 方法,这会更快一些:

    import numpy as np
    import re
    
    try:
        # Python2
        import string
        table = string.maketrans('()','  ')
    except AttributeError:
        # Python3
        table = bytes.maketrans(b'()',b'  ')
    
    with open('data', 'rb') as f:
        lines = (line.translate(table) for line in f)
        arr = np.genfromtxt(lines)
    print(arr)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-14
      • 2019-06-20
      • 1970-01-01
      • 2016-01-05
      • 2018-05-17
      • 2018-06-10
      相关资源
      最近更新 更多