Python study notes-text file

1. Convert a text file to a list

with open('C:/Users/wxscn/Desktop/predefined_classes.txt', 'r', encoding='utf-8') as f:
	classList = f.read().split('\n')
print(classList)

Running result: ['air hole','slag inclusion','weld bump','crack','undercut']

2. First convert the text file to a list, and then convert the list to a matrix. Linear algebra operations can only be performed after the list is converted to a matrix, otherwise an alarm will be generated: TypeError: list indices must be integers or slices, not tuple

import numpy as np
from matplotlib import pyplot as plt
with open('C:/Users/wxscn/Desktop/curve.txt', 'r', encoding='utf-8') as f:
	lines = f.read().split('\n')
# 将文本文件转换为列表
data = [line.split(' ') for line in lines]
# 将列表转换为矩阵,后续进行线性代数操作
data = np.mat(data)
# 去掉一头一尾,截取部分数据,此操作视需求而定
x = data[1:-1, 1]
y = data[1:-1, 2]
# 绘制曲线
plt.plot(x, y, '-r', label = 'exponential curve', linewidth = 3.0)
plt.title('sample')
plt.xlabel('x', fontsize = 12)
plt.ylabel('y', fontsize = 12)
plt.show()

Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/wxsy024680/article/details/114895858