Python 如何将数组从.txt文件导入numpy数组?
如果这是super noob,我深表歉意,但我已经尝试在StackOverflow上搜索过了,当已经存在“[”或“[[”字符时,找不到如何将数组从文本文件导入numpy数组 上下文:我将系统日志输出保存到一个文本文件中,并尝试使用np.genfromtxt()和np.loadtxt()。此外,数组实际上是高度结构化的,(它们总是10列,但我的结果文本文件将一行10列拆分为一行(比如6列)和另一行4列。我想知道是否已经有一种内置方法可以读取这些数据,而不必在“[”处声明“开始新行”,在“]”处声明“结束行”) [-3.81266403e-07-2.30981200e-07-7.07703123e-08-9.66262661e-08 -3.73168461e-07-2.65608435e-07-2.38021940e-07 3.23960222e-07Python 如何将数组从.txt文件导入numpy数组?,python,arrays,numpy,import,genfromtxt,Python,Arrays,Numpy,Import,Genfromtxt,如果这是super noob,我深表歉意,但我已经尝试在StackOverflow上搜索过了,当已经存在“[”或“[[”字符时,找不到如何将数组从文本文件导入numpy数组 上下文:我将系统日志输出保存到一个文本文件中,并尝试使用np.genfromtxt()和np.loadtxt()。此外,数组实际上是高度结构化的,(它们总是10列,但我的结果文本文件将一行10列拆分为一行(比如6列)和另一行4列。我想知道是否已经有一种内置方法可以读取这些数据,而不必在“[”处声明“开始新行”,在“]”处声明
-1.73911175e-07-4.02730223e-07]这些读卡器使用的是由一些定义良好的分隔符分隔的
csv
-数字列。像这样的外来字符[]会使简单的读取变得混乱。感谢您的快速响应!但是,它返回一个错误:SyntaxError:无效语法“并且只指向整个文本块。@CodeinCafes抱歉:(谢谢!它仍然失败,但我意识到发生了什么。我在每行的第一个元素前面都有空格。我删除了空格,从而呈现了数组。太感谢了!太棒了。只勾选了:-)需要获得更多的代表点数才能向上投票…再次感谢!!
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)
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)