首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python numpy.genfromtxt

Python numpy.genfromtxt
EN

Stack Overflow用户
提问于 2015-06-26 01:17:02
回答 1查看 329关注 0票数 0

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

代码语言:javascript
复制
1.466 ((5.68 3.3 45.7)(4.5 6.7 9.5))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-26 02:13:49

np.genfromtxt可以接受迭代器:

代码语言:javascript
复制
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)

收益率

代码语言:javascript
复制
[  1.466   5.68    3.3    45.7     4.5     6.7     9.5  ]

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

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31063372

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档