本文參考:《機器學習算法原理與編程實踐》鄭捷,第1章第四節
本文程序中使用的txt數據截圖如下圖。數據鏈接:https://pan.baidu.com/s/1_Ce6WLGDTWf7qQIvpP-70Q ,提取碼:n22a
python讀入該數據,並轉成array,代碼如下:
import os import numpy as np # 數據文件轉矩陣 # path: 數據文件路徑 # delimiter: 行內字段分隔符 def file2array(path, delimiter): recordlist = [] fp = open(path, 'r', encoding='utf-8') content = fp.read() # content現在是一行字符串,該字符串包含文件所有內容 fp.close() rowlist = content.splitlines() # 按行轉換為一維表,splitlines默認參數是‘\n’ # 逐行遍歷 # 結果按分隔符分割為行向量 recordlist = [row.split(delimiter) for row in rowlist if row.strip()] return np.array(recordlist) root = 'testdata' filelist = os.listdir(root) # 獲取路徑下所有數據文件的文件名 for file in filelist[:-1]: recordArray = file2array(root + '/' + file, '\t') # 文件到矩陣的轉換 print('shape of recordmat: ', np.shape(recordArray))
結果如下: