Python3 入门学习

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27087571/article/details/80556079

python 入门学习

 开发需求

最近项目中使用到了pid算法,为了找到合适的参数,以及清楚地了解pid的运行情况.因此想要将pid的数据
用上位机画出来.以前都是使用串口来做的,但是现在的项目中,只有使用网口比较方便,这样合适的上位机就
只好由自己来写了.需求比较简单只要将下位机发送上来的特定数据,实时在电脑上绘制成曲线就可以了,不同
的曲线使用不同的颜色标记出来.

开发环境的搭建

本来准备直接在ubuntu上写代码的,但是因为会使用到很多的库,因此决定安装anaconda这样各种库都有
了,免得自己安装太麻烦了.然后安装spyder可视化的ide环境,还是蛮好用的.

python 简单的概念

文件操作函数:

  • 打开文件的模式有:
    1. 只读模式(默认)
    2. 只写模式(不可读,不存在则创建,存在则覆盖)
    3. 追加模式(可读,不存在则创建,存在则只追加内容)

  • “+”表示可同时读写某个文件:
    1. r+可读写文件(可读,可写,可追加)
    2. w+写读
    3.a+追加

  • 基本函数:

1. 打开文件open()

    f = open('test.txt','r+')

2.关闭文件

f = open('test.txt','r+',encoding='utf-8')

3.读取文件内容(可指定每次读取字字符)

f = open('test.txt','r+',encoding='utf-8')
ret = f.read(8)
print(ret)

4.读取一行数据

f = open('test.txt','r+',encoding='utf-8')
ret = f.readline()
print(ret)
f.close()

5. 写入文件,writelines()参数是序列,比如列表,它会迭代帮你写入文件

f = open('test.txt','a+',encoding='utf-8')
f.writelines(["aa","bb","cc"])
ret = f.read()
print(ret)
f.close()
  1. 读取字符
f = open('test.txt','r+',encoding='utf-8')
ret = f.read(8)     #先读取8个字符

循环语句的使用

  • 循环的使用
while 判断条件:
    语句
  • 退出循环
break;

数组的使用

强制转换

  • 有时候,我们需要对数据内置的类型进行转换,数据类型的转换,你只需要将数据类型作为函数名即可。
int(x)x转换为一个整数。

字符串函数处理

简单示例代码

"""
# -*- coding: utf-8 -*-

# head: draw1:  
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import sys
import io

def draw_lines(x,y,descrip):
    plt.plot(x, y, marker='o', mec='r', mfc='w',label=descrip)

x_list      = []
y_list      = []

head = "draw"

line_count = 0
node_count = 0
line_discrip = "NULL"

print(sys.argv[1])
f = io.open(sys.argv[1],'r',encoding='utf-8')
#f = open('sys.argv[1]','r',encoding='utf-8')
while 1:

    while 1:
        line = f.readline()  
        flag = head + str(line_count)
        if(flag in line) :
            line_discrip    = line.split()[1]  
            value           = line.split()[2] 
            float_value           = float(value)
            x_list.append(node_count)
            y_list.append(float_value)
            node_count      = node_count + 1    
        else: 
            if not line: 
                line_count = line_count+1
                if (node_count > 1):
#                    print("y_list", y_list)
                    draw_lines(x_list, y_list, line_discrip);
                node_count = 0
                x_list = []
                y_list = []
                f.seek(0,0)
                break;

    if(line_count > 10) :
        break;   


plt.legend()

plt.xlabel("Time") 
plt.ylabel("Value") 
plt.title("Data Flow")   
plt.show()
f.close()

运行结果

猜你喜欢

转载自blog.csdn.net/qq_27087571/article/details/80556079