使用read()从文件中获取Numpy数组(Python)

2024-03-29 01:18:44 发布

您现在位置:Python中文网/ 问答频道 /正文

对于文本文件(testfile.txt):

# blah blah blah

Unpleasant astonished an diminution up. Noisy an their of meant. Death means up civil do an offer wound of. 
//Called square an in afraid direct. 


{Resolution} diminution conviction so (mr at) unpleasing simplicity no. 
/*No it as breakfast up conveying earnestly 

numpy数组中存储文本文件的内容时,我很难理解这两者之间的区别:

A.当文本文件直接打开(不带read())并存储在numpy数组中时,以及

当文本文件第一次用read()打开,然后存储在numpy数组中时。在

代码如下:

^{pr2}$

我的问题是如何更改numpy.array([str(i) for i in f])命令,以便生成的numpy数组以输出A的方式保存文本文件的内容(如下所示)。在

输出:

A
['# blah blah blah\n' '\n'
 'Unpleasant astonished an diminution up. Noisy an their of meant. Death means up civil do an offer wound of. \n'
 '//Called square an in afraid direct. \n' '\n' '\n'
 '{Resolution} diminution conviction so (mr at) unpleasing simplicity no. \n'
 '/*No it as breakfast up conveying earnestly ']

B
['#' ' ' 'b' 'l' 'a' 'h' ' ' 'b' 'l' 'a' 'h' ' ' 'b' 'l' 'a' 'h' '\n' '\n'
 'U' 'n' 'p' 'l' 'e' 'a' 's' 'a' 'n' 't' ' ' 'a' 's' 't' 'o' 'n' 'i' 's'
 'h' 'e' 'd' ' ' 'a' 'n' ' ' 'd' 'i' 'm' 'i' 'n' 'u' 't' 'i' 'o' 'n' ' '
 'u' 'p' '.' ' ' 'N' 'o' 'i' 's' 'y' ' ' 'a' 'n' ' ' 't' 'h' 'e' 'i' 'r'
 ' ' 'o' 'f' ' ' 'm' 'e' 'a' 'n' 't' '.' ' ' 'D' 'e' 'a' 't' 'h' ' ' 'm'
 'e' 'a' 'n' 's' ' ' 'u' 'p' ' ' 'c' 'i' 'v' 'i' 'l' ' ' 'd' 'o' ' ' 'a'
 'n' ' ' 'o' 'f' 'f' 'e' 'r' ' ' 'w' 'o' 'u' 'n' 'd' ' ' 'o' 'f' '.' ' '
 '\n' '/' '/' 'C' 'a' 'l' 'l' 'e' 'd' ' ' 's' 'q' 'u' 'a' 'r' 'e' ' ' 'a'
 'n' ' ' 'i' 'n' ' ' 'a' 'f' 'r' 'a' 'i' 'd' ' ' 'd' 'i' 'r' 'e' 'c' 't'
 '.' ' ' '\n' '\n' '\n' '{' 'R' 'e' 's' 'o' 'l' 'u' 't' 'i' 'o' 'n' '}' ' '
 'd' 'i' 'm' 'i' 'n' 'u' 't' 'i' 'o' 'n' ' ' 'c' 'o' 'n' 'v' 'i' 'c' 't'
 'i' 'o' 'n' ' ' 's' 'o' ' ' '(' 'm' 'r' ' ' 'a' 't' ')' ' ' 'u' 'n' 'p'
 'l' 'e' 'a' 's' 'i' 'n' 'g' ' ' 's' 'i' 'm' 'p' 'l' 'i' 'c' 'i' 't' 'y'
 ' ' 'n' 'o' '.' ' ' '\n' '/' '*' 'N' 'o' ' ' 'i' 't' ' ' 'a' 's' ' ' 'b'
 'r' 'e' 'a' 'k' 'f' 'a' 's' 't' ' ' 'u' 'p' ' ' 'c' 'o' 'n' 'v' 'e' 'y'
 'i' 'n' 'g' ' ' 'e' 'a' 'r' 'n' 'e' 's' 't' 'l' 'y' ' ']

Tags: ofinnumpyan数组blah文本文件up
1条回答
网友
1楼 · 发布于 2024-03-29 01:18:44

只需将read()的输出拆分为单独的行:

def load_entire_file_into_memory_and_then_convert(filename):
  with open(filename, 'r') as input_file:
     full_file_contents = input_file.read()
     lines_of_file = full_file_contents.split('\n')
     return numpy.array(lines_of_file)

你的另一个版本是:

^{pr2}$

请注意这两个版本之间的语义差异,以及为什么会得到不同的结果;当你“为。。。在“on a file”中,返回的结果是单独的行。如果您调用read(),那么您将整个文件作为单个字符串(用换行符分隔的行)和“for…”。。。在“on a string”中提供字符串的单个字符(而不是行)。虽然在某些情况下,使用read()更方便(例如,当您真的想一次加载所有行时),但是逐行处理文件通常更具伸缩性/更好的习惯(使用第一种方法),因为这样可以减少内存占用(例如在其他应用程序中,不要求所有行同时都在内存中,并且一次只能操作文件的一行)。在

相关问题 更多 >