für eine Textdatei (testfile.txt
):Numpy Array aus einer Datei mit read() (Python)
# 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
Wenn innerhalb eines numpy Array den Inhalt einer Textdatei zu speichern, ich habe Probleme beim Verständnis der Differenz zwischen:
A., wenn die Textdatei geöffnet wird direkt (ohne read()
) und im numpy Array gespeichert, und
B., wenn die Textdatei zuerst mit einemgeöffnet wird 0 und dann in der Numy-Array gespeichert. Hier
ist der Code:
import numpy
# open directly with no read
a = numpy.array([str(i) for i in open(r'C:\testfile.txt', 'r')])
# open with read then store in numpy *how I want to do it*
f = open(r'C:\testfile.txt', 'r').read()
b = numpy.array([str(i) for i in f])
print("A")
print(a)
print()
print("B")
print(b)
Meine Frage ist wie der numpy.array([str(i) for i in f])
Befehl zu ändern, so dass der resultierende numpy Array den Inhalt der Textdatei in der Art und Weise hält, dass Ausgang A tut (siehe unten).
Ausgang:
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' ' ']
Bei Textdateien ist 'readlines()' normalerweise nützlicher als 'read()'. Das Ergebnis ähnelt der Iteration in der geöffneten Datei. – hpaulj
Einverstanden. readlines() ist im Prinzip dasselbe wie "for ... in" für das Dateiobjekt. Die Frage lautet jedoch direkt, wie man es mit "read()" macht. –