Python学习笔记——文本文件

1、将文本文件转换为列表

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

运行结果:[‘气孔’, ‘夹渣’, ‘焊瘤’, ‘裂纹’, ‘咬边’]

2、先将文本文件转换为列表,再将列表转换为矩阵。列表转换为矩阵之后才可以进行线性代数操作,否则产生报警: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()

在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wxsy024680/article/details/114895858