从.txt文件中读取第N行(Python) [英] Reading every Nth line from a .txt file (Python)

查看:5129
本文介绍了从.txt文件中读取第N行(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,该程序从.txt文件读取时间值和读数,并使用matplotlib将其绘制在网页上.在我的情况下,有很多值,并且该图看起来非常混乱,并且具有成千上万个数据点,它也可能很慢.

I am making a program that reads time values and readings from a .txt file and plots them on a web-page with matplotlib. In my case there are lots of values, and the plot can look very confusing, and with thousands of data points it can also be sluggish.

我目前正在使用以下代码读取.txt行,以将值放入绘图表列表中:

I am currently reading the .txt lines with this code to put the values into plottable lists:

with open('C:/Email/file.txt') as f:   


    lines = f.readlines()



    dates = [str(line.split(';')[0]) for line in lines]
    y = [float(line.split(';')[1]) for line in lines]
    z = [float(line.split()[2]) for line in lines]

.txt文件的内容如下:

The .txt file content looks like this:

30.05.18_12:27:17;  13.0;  -0.0
30.05.18_12:27:18;  14.0;  -0.0
30.05.18_12:27:19;  15.0;  -0.0
30.05.18_12:27:20;  16.0;  -0.0

那么,是否有任何方法可以读取和绘制每N分之一的时间戳和值(例如,每30个就比较理想)?

So, is there any way to read and plot every Nth (for example every 30. would be ideal) timestamp and value?

我一直在研究不同的方法,但是它们似乎令人困惑.

I've been researching different ways but they seem confusing.

我正在考虑的一种解决方案是创建一个计数器,用于对读取行的数量进行计数,然后当计数器为30时,跳过30行,然后在第31行读取并绘制数据.我不知道该怎么做这样做,因为我是Python的新手.

One solution that I was thinking about is to make a counter that counts the amount of read lines, then when the counter is 30, skip 30 the next lines and read and plot the data in line 31. I have no idea how to do this, since I am relatively new to Python.

我们将不胜感激.

以防万一,整个代码在这里:

Just in case, the whole code here:

from flask import Flask
import numpy as np
import matplotlib.pyplot as plt, mpld3
from datetime import datetime

app = Flask(__name__)



@app.route("/")
def hello():

    with open('C:/Email/file.txt') as f:   


        lines = f.readlines()



        dates = [str(line.split(';')[0]) for line in lines]
        y = [float(line.split(';')[1]) for line in lines]
        z = [float(line.split()[2]) for line in lines]


        date = [datetime.strptime(x,'%d.%m.%y_%H:%M:%S') for x in dates]
        plt.figure(figsize=(10,5))
        plt.title('Temperature', fontsize=15)
        plt.ylabel('Temperature' + u'\u2103', fontsize=15)

        plt.plot_date(date, y, 'r-', label='quadratic')
        plt.ylim([10,35])

        # Print as HTML
        return mpld3.show()

if __name__ == "__main__":
    app.run()

编辑:非常感谢MR. F-ROCHE

HUGE THANKS TO MR. F-ROCHE

使用以下代码进行操作:

Got it working with the following code:

@app.route("/")
def hello():

    with open('C:/Email/file.txt') as f:   

        # Counts lines in text (Use later to delete lines every X readings)
        # lines = f.readlines()
        cpt = 0
        all_lines = []
        for line in f:
            cpt += 1
            if cpt == 30:
                all_lines.append(line)
                cpt = 0
        dates = [str(line.split(';')[0]) for line in all_lines]
        date = [datetime.strptime(x,'%d.%m.%y_%H:%M:%S') for x in dates]
        y = [float(line.split(';')[1]) for line in all_lines]
        z = [float(line.split()[2]) for line in all_lines]

        plt.figure(figsize=(10,5))
        plt.title('Temperature', fontsize=15)
        plt.ylabel('Temperature' + u'\u2103', fontsize=15)


        plt.plot_date(date, y, 'r-', label='quadratic')
        plt.ylim([10,35])

        # Print as HTML
        return mpld3.show()

推荐答案

类似的内容仅每30行显示一次:

Something like that will only display every 30 lines:

with open('C:/Email/file.txt') as f:
    cpt = 0
    for line in f:
        cpt += 1
        if cpt == 30:
            print(line)
            cpt = 0

您可以将line变量放在这样的列表中:

you can put line variable in a list like this:

all_lines = []
...
all_lines.append(line)

或者用一行代码甚至更好:

or even better with one line of code:

with open('C:/Email/file.txt') as f:
    all_lines = [v for i, v in enumerate(f, start=1) if i % 30 == 0]

然后,您可以将其应用于datesyz.

Then you can apply that to dates, y and z instead.

这篇关于从.txt文件中读取第N行(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆