从Python中的TXT文件中提取两列数字并绘制它们



我在Pycharm中需要一些非常基本的帮助。我正在尝试从.txt文件中提取两列数字(但是每列中的数字数量是更改的(,然后绘制它们。到目前为止,这是我的代码。

pacient = str(input("Please enter your the name of the pacient: "))
Pname = pacient+'.txt'
print(Pname)
file  = open(Pname,"r")
print (file.read())
# what i need in here is save the first column of the .txt in 't' and the second one in 'v'. 

import matplotlib.pyplot as plt
plt.plot(t, v)
plt.xlabel('time (v)')
plt.ylabel('Velocity (m/s)')
plt.title(pacient+"plot")
plt.savefig("test.png")
plt.show()

您可以使用csv模块读取文件:

import csv
t = []
v = []
with open(Pname, "r") as patient_f:
    csv_f = csv.reader(patient_f, delimieter='delimiter_between_columns')
    for row in csv_f:
        t.append(row[0])
        v.append(row[1])

您可以做的就是使用numpy为您订购列:

import numpy as np
file = np.loadtxt("filename.txt", delimiter=',') #do not need delimiter if your file is not csv. 
t = file[:,0]
v = [:,1]
plt.plot(t, v)
plt.show()
plt.xlabel('time (v)')
plt.ylabel('Velocity (m/s)')
plt.title(pacient+"plot")
plt.savefig("test.png")
plt.show()

没有numpy的另一种方式:

file = open('filename.txt').readlines()
file = [map(int, i.strip('n').split()) for i in file]
new_data = [list(i) for i in zip(*file)]
plt.plot(new_data[0], new_data[1])
plt.show()

相关内容

最新更新