简体   繁体   English

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

[英]Extracting two columns of numbers from a txt file in python and plot them

I need some very basic help with Python in PyCharm. 我需要在PyCharm中使用Python的一些非常基本的帮助。 I'm trying to extract two columns of numbers from a .txt file(But the amount of numbers in each column is something that changes ) and then plot them. 我正在尝试从.txt文件中提取两列数字(但是每列中的数字量会发生变化),然后绘制它们。 So far that's my code. 到目前为止,这就是我的代码。

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()

You can use csv module to read the file: 您可以使用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])

what you can do is use numpy to order the columns for you: 您可以使用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()

Another way without numpy: 没有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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM