【问题标题】:How to import arrays from a .txt file to numpy arrays?如何将数组从 .txt 文件导入到 numpy 数组?
【发布时间】:2018-08-11 03:22:41
【问题描述】:

抱歉,如果这是超级菜鸟,但我已经尝试在 StackOverflow 上进行搜索,但无法找到当已经存在“[”或“[[”字符时如何将数组从文本文件导入到 numpy 数组.

上下文:我将系统日志输出保存到一个文本文件中,并尝试使用 np.genfromtxt() 和 np.loadtxt()。此外,数组实际上是高度结构化的(它们总是 10 列,但我生成的文本文件将单行 10 列拆分为一行,例如 6 列和另一列 4 列。我想知道是否已经一种读取此数据的内置方式,无需在“[”处声明“开始新行”并在“]”处声明结束行。

[[  2.16089589e-07  -2.41978796e-07   5.81936831e-07   2.67195929e-07
1.41540781e-07  -2.39142167e-07   2.11576619e-07   2.70369611e-07
3.11488321e-07   1.41789783e-07]

[ -3.81266403e-07 -2.30981200e-07 -7.07703123e-08 -9.66262661e-08 -3.73168461e-07 -2.65608435e-07 -2.38021940e-07 3.23960222e-07 -1.73911175e-07 -4.02730223e-07]]

【问题讨论】:

  • 这些读者使用csv - 由一些定义明确的分隔符分隔的数字列。像这些 [] 这样的无关字符会打乱简单的阅读。

标签: python arrays numpy import genfromtxt


【解决方案1】:
from numpy import array   

with open("your_file.txt", "r") as myFile: ## Open (and close) your file

    arr = ""
    for line in myFile:
        arr += line.replace("\n", "") ## Replace each newline character in each line so that arr is just one long continuous string
    arr = " ".join(arr.split()) ## Replace multiple whitespace with single spaces
    arr = arr.replace(" ", ",") ## Replace the spaces with commas (so that it can be interpreted as a list
    arr = eval(arr) ## The text will now be stored as a list
    arr = array( arr ) ## Now it's a numpy array (hopefully)

【讨论】:

  • 感谢您的快速响应!但是,它返回一个错误:SyntaxError: invalid syntax",并且只指向整个文本块。
  • @CodeinCafes 对不起:(
  • 谢谢!它仍然失败,但我意识到发生了什么。我在每行的第一个元素之前有空格。我删除了空格,然后渲染了数组。非常感谢!太棒了。
  • 刚刚打勾 :-) 需要获得更多代表点来支持...再次感谢!!
猜你喜欢
  • 2017-01-21
  • 2018-12-15
  • 2015-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-22
  • 1970-01-01
相关资源
最近更新 更多