簡體   English   中英

從python的txt文件中提取兩列數字並繪制它們

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

我需要在PyCharm中使用Python的一些非常基本的幫助。 我正在嘗試從.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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM