The python like txt file data read method numpy array

Xiao Bian today to share data such as a python to txt file for everyone to read numpy array method, a good reference value, we want to help. Xiao Bian together to follow up to see it
in practice, a lot of data files are saved as a txt, csv files, but when dealing in the program numpy array or list is the most convenient. This paper briefly describes the txt file and convert it into a method numpy array or list of reading.

1 txt file list is read and converted into numpy array

import numpy as np
  
file = open('filename.txt')
val_list = file.readlines() 
lists =[]
for string in val_list:
 string = string.split('\t',3)
lists.append(string[0:2]) #只取每个string的前两项,得到的lists即为所要的列表
a = np.array(lists) #将列表转化为numpy数组,
a= a.astype(int) #并设定类型为intfile.close()

This method, although the code a little longer, but you can allow your txt file in each line contains both digital items contain letters and other items, If every item numbers for each line of your txt file, then there a simpler method:

a = numpy.loadtxt('filename.txt')

Such directly numpy array as a whole number.

About 2 split method, etc.

split function separated by a specified string delimiter, if the parameter has the value num, said partition string num string. Syntax: string.split (str = "", num = x), str a delimiter, the default is all null characters, such as spaces, line breaks, tabs, and the like. num is the number of sub-strings. Returns the list of strings is separated. As described above in a solid column:

string = string.split('\t',3)

Expressed as \ t a delimiter, divided into three strings. Addition to the usual split, there is a commonly used functions related functions strip (), which is used to remove the head and tail of the specified string of characters. Its syntax: string.strip ([char]), char is

To remove the characters specified, the default is a space. Returns a new string value removed. Real are listed below:

str = "000111aaabbb111000"
print str.strip('0')

The output is:

111aaabbb111

This python above the data read txt and other documents for numpy array of small series is to share with you the entire contents of the
write to you, for everyone to recommend a very wide python learning resource gathering, click to enter, there are senior Share programmer before learning

Experience, study notes, there is a chance of business experience, and for everyone to carefully organize a python to combat zero-based item of information,

Python day to you on the latest technology, prospects, learning to leave a message of small details

Published 78 original articles · won praise 25 · views 120 000 +

Guess you like

Origin blog.csdn.net/haoxun11/article/details/105210892