簡體   English   中英

使用python生成一維數組形式txt文件

[英]Generate 1d array form txt file using python

我是python的新手。對於我的拼貼項目需要開發一些程序,為了進行數據分析,我使用了大量的數組,這些數組的值取自文本文件。txt文件中的值如下

 0 0 0 0,0,0 0,0,0,0,0,0 0,0 0,0,0 

我想在1維數組中進行轉換,例如[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

我該怎么做。 謝謝

我得到了一些完整的幫助代碼,但無法正常工作,但出現了一些我無法識別的錯誤

path2='page_2.txt'
input2 = np.array(np.loadtxt(path2, dtype='i', delimiter=','))

錯誤:

 ValueError Traceback (most recent call last) <ipython-input-139-8836e57e833d> in <module> 5 6 path2='page_2.txt' ----> 7 input2 = np.array(np.loadtxt(path2, dtype='i', delimiter=',')) 8 9 path3='page_4.txt' ~\\Anaconda3\\lib\\site-packages\\numpy\\lib\\npyio.py in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin, encoding) 1099 # converting the data 1100 X = None -> 1101 for x in read_data(_loadtxt_chunksize):1102 if X is None:1103 X = np.array(x, dtype) ~\\Anaconda3\\lib\\site-packages\\numpy\\lib\\npyio.py in read_data(chunk_size) 1023 line_num = i + skiprows + 1 1024 raise ValueError("Wrong number of columns at line %d" -> 1025 % line_num)1026 1027# Convert each value according to its column and store 

ValueError:第4行的列數錯誤

這是因為第4行(即0,0,0)具有三列,而不是前三行。

相反,您可以做的是連接所有行並將其轉換為數組:

with open(path2) as f:
    str_arr = ','.join([l.strip() for l in f])

int_arr = np.asarray(str_arr.split(','), dtype=int)

print(int_arr)
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

如果我理解正確,那么您希望將整個文件中的所有元素都放在一個數組中。

可以這樣完成:

with open(filename) as f:
    numbers = [
        e
        for line in f
        for e in line.strip().split(',')]

int_arr = np.asarray(numbers, dtype=int)

之后,我們有:

>>> print(int_arr)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM