Python QuickStart

来自Jack's Lab
(版本间的差异)
跳转到: 导航, 搜索
(Quick Start)
(Format)
 
(未显示1个用户的31个中间版本)
第1行: 第1行:
 
== Quick Start ==
 
== Quick Start ==
  
Install python3.8 from https://www.python.org/downloads/
+
* Install python3.8 from https://www.python.org/downloads/
 +
** Windows: https://www.python.org/ftp/python/3.8.1/python-3.8.1-amd64.exe
 +
** Mac OS X: https://www.python.org/ftp/python/3.8.1/python-3.8.1-macosx10.9.pkg
  
  
第16行: 第18行:
 
<source lang=bash>
 
<source lang=bash>
 
$ sudo pip3 install numpy pandas matplotlib
 
$ sudo pip3 install numpy pandas matplotlib
 +
$ sudo pip3 install scipy
 
$ sudo pip3 install tensorflow
 
$ sudo pip3 install tensorflow
 
</source>
 
</source>
第21行: 第24行:
  
 
[https://www.jianshu.com/p/91365f343585 Jupyter Notebook介绍、安装及使用教程]
 
[https://www.jianshu.com/p/91365f343585 Jupyter Notebook介绍、安装及使用教程]
 +
 +
<source lang=bash>
 +
$ pip3 install --upgrade pip
 +
$ pip3 install jupyter
 +
</source>
  
 
<br><br>
 
<br><br>
 +
 +
== Bytes to string ==
 +
 +
* https://blog.csdn.net/sinat_41104353/article/details/79283619
 +
 +
<br>
  
 
== Basics ==
 
== Basics ==
第202行: 第216行:
 
Jack wrote Hello world
 
Jack wrote Hello world
 
</source>
 
</source>
 +
 +
<br><br>
 +
 +
=== yield ===
 +
 +
类 return 作用,不过返回的是生成器,可以用 for ... in generator 或 next 遍历该生成器
 +
 +
* https://zhuanlan.zhihu.com/p/268605982
  
 
<br><br>
 
<br><br>
第257行: 第279行:
 
== Data Structures ==
 
== Data Structures ==
  
<br><br>
+
=== Dict ===
 +
 
 +
* https://www.runoob.com/python3/python3-dictionary.html
 +
* https://www.jianshu.com/p/e6627929d379
 +
 
 +
<br>
 +
 
 +
=== List ===
 +
 
 +
中括号 [] 声明
 +
 
 +
* https://www.runoob.com/python3/python3-list.html
 +
 
 +
<br>
 +
 
 +
=== 元组 ===
 +
 
 +
括号声明,一旦定义 元素不可更改
 +
 
 +
* https://www.runoob.com/python3/python3-tuple.html
 +
 
 +
<br>
  
 
== Exceptions ==
 
== Exceptions ==
第300行: 第343行:
 
* [https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html matplotlib.pyplot.plot()]
 
* [https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html matplotlib.pyplot.plot()]
 
* [https://matplotlib.org/api/_as_gen/matplotlib.pyplot.figure.html matplotlib.pyplot.figure()]
 
* [https://matplotlib.org/api/_as_gen/matplotlib.pyplot.figure.html matplotlib.pyplot.figure()]
 +
 +
* [https://matplotlib.org/gallery/text_labels_and_annotations/annotation_demo.html Annotating Plots]
 +
* [https://matplotlib.org/tutorials/introductory/customizing.html Customizing Matplotlib with style sheets and rcParams ]
  
 
<br>
 
<br>
第307行: 第353行:
 
* [https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html#matplotlib.pyplot.bar matplotlib.pyplot.bar]
 
* [https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html#matplotlib.pyplot.bar matplotlib.pyplot.bar]
 
* [https://matplotlib.org/api/_as_gen/matplotlib.pyplot.annotate.html#matplotlib.pyplot.annotate matplotlib.pyplot.annotate]
 
* [https://matplotlib.org/api/_as_gen/matplotlib.pyplot.annotate.html#matplotlib.pyplot.annotate matplotlib.pyplot.annotate]
 +
 +
<source lang=python>
 +
def currency(x, pos):
 +
    """The two args are the value and tick position"""
 +
    if x >= 1e6:
 +
        s = '${:1.1f}M'.format(x*1e-6)
 +
    else:
 +
        s = '${:1.0f}K'.format(x*1e-3)
 +
    return s
 +
 +
formatter = FuncFormatter(currency)
 +
 +
fig, ax = plt.subplots(figsize=(6, 8))
 +
ax.xaxis.set_major_formatter(formatter)
 +
</source>
  
 
<br>
 
<br>
第313行: 第374行:
  
 
* [https://matplotlib.org/gallery/statistics/histogram_cumulative.html?highlight=cdf hist.cdf]
 
* [https://matplotlib.org/gallery/statistics/histogram_cumulative.html?highlight=cdf hist.cdf]
 +
 +
<br>
 +
 +
== Numpy ==
 +
 +
[https://www.delftstack.com/zh/howto/numpy/save-numpy-array-as-image/ 在 Python 中将 NumPy 数组保存为图像]
 +
 +
<source lang=python>
 +
import numpy as np
 +
import matplotlib.pyplot as plt
 +
 +
ds = np.arange(0,737280, 1, np.uint8)
 +
ds = np.reshape(ds, (1024, 720))
 +
 +
plt.imsave('test.jpg', ds)
 +
</source>
 +
 +
<br>
 +
 +
== Seaborn ==
 +
 +
* https://seaborn.pydata.org/examples/
 +
* [https://www.jianshu.com/p/5ff47c7d0cc9 Seaborn Intro]
 +
* https://zhuanlan.zhihu.com/p/24464836
 +
 +
<br>
 +
 +
=== Panel ===
 +
 +
* https://panel.holoviz.org/gallery/index.html
  
 
<br>
 
<br>
第388行: 第479行:
 
print(resp)
 
print(resp)
 
</source>
 
</source>
 +
  
 
使用post方式时,数据放在 data 或者 body 中:
 
使用post方式时,数据放在 data 或者 body 中:
第405行: 第497行:
 
</source>
 
</source>
  
Reference: https://blog.csdn.net/lovemysea/article/details/77776299
+
 
 +
'''Python3:'''
 +
 
 +
<source lang=python>
 +
import urllib.request as http
 +
 
 +
resp = http.urlopen('http://iot.xxx.net')
 +
# print(resp.info())
 +
resp.read()
 +
resp.close()
 +
</source>
 +
 
 +
Reference: https://docs.python.org/3.8/library/urllib.request.html#module-urllib.request
 +
 
 +
* https://www.jianshu.com/p/491d6590b2a0
 +
 
 +
<br>
 +
 
 +
== CSV ==
 +
 
 +
<source lang=python>
 +
import csv
 +
csvfile = open('data-text.csv', 'rb')
 +
reader = csv.reader(csvfile)
 +
for row in reader:
 +
    print row
 +
</source>
  
 
<br>
 
<br>
  
 
=== Time ===
 
=== Time ===
 +
 +
<br>
 +
 +
=== PDF ===
 +
 +
* https://github.com/jsvine/pdfplumber
 +
 +
<source lang=bash>
 +
$ pip3 install pdfplumber
 +
</source>
 +
 +
Refer to: https://zhuanlan.zhihu.com/p/40221732
 +
 +
<source lang=python>
 +
import pdfplumber
 +
import pandas as pd
 +
 +
pdf = pdfplumber.open('ncp-who.pdf')
 +
page0 = pdf.pages[0]              #PDF 文件的第一页
 +
table = page0.extract_table()
 +
d = pd.DataFrame(table)
 +
 +
print(d.loc[0])
 +
d.to_csv('ncp-who.csv', index = False, header = True, date_format='%Y%m%d')
 +
</source>
 +
 +
复杂的,参考:https://github.com/jsvine/pdfplumber/blob/master/examples/notebooks/extract-table-nics.ipynb
 +
 +
<br><br>
 +
 +
== getopt ==
 +
 +
=== sys ===
 +
 +
<source lang=python>
 +
import sys
 +
print(sys.argv[0])
 +
 +
for i in range(1, len(sys.argv)):
 +
    print (i, sys.argv[i])
 +
</source>
 +
 +
<source lang=bash>
 +
$ python test.py hello world
 +
test.py
 +
1 hello
 +
2 world
 +
</source>
 +
 +
<br>
 +
 +
=== getopt ===
 +
 +
<source lang=python>
 +
import sys, getopt
 +
 +
opts, args = getopt.getopt(sys.argv[1:], "hi:o:")
 +
input_file=""
 +
output_file=""
 +
for op, value in opts:
 +
    if op == "-i":
 +
        input_file = value
 +
    elif op == "-o":
 +
        output_file = value
 +
    elif op == "-h":
 +
        usage()
 +
        sys.exit()
 +
 +
def main(argv):
 +
  inputfile = ''
 +
  outputfile = ''
 +
  try:
 +
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
 +
  except getopt.GetoptError:
 +
      print ('test.py -i <inputfile> -o <outputfile>')
 +
      sys.exit(2)
 +
  for opt, arg in opts:
 +
      if opt == '-h':
 +
        print ('test.py -i <inputfile> -o <outputfile>')
 +
        sys.exit()
 +
      elif opt in ("-i", "--ifile"):
 +
        inputfile = arg
 +
      elif opt in ("-o", "--ofile"):
 +
        outputfile = arg
 +
  print ('Input file is "', inputfile)
 +
  print ('Output file is "', outputfile)
 +
 +
if __name__ == "__main__":
 +
  main(sys.argv[1:])
 +
</source>
  
 
<br>
 
<br>
第418行: 第626行:
  
 
* Python Quick Start: http://www.tutorialspoint.com/python/python_lists.htm
 
* Python Quick Start: http://www.tutorialspoint.com/python/python_lists.htm
 +
 +
* Python 命令行参数:https://blog.csdn.net/power721/article/details/8749576
  
 
* [[Color]]
 
* [[Color]]

2022年4月8日 (五) 17:39的最后版本

目录

[编辑] 1 Quick Start


Install pip:

$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
$ sudo python get-pip.py


Using the pip to install the numpy and tensorflow package:

$ sudo pip3 install numpy pandas matplotlib
$ sudo pip3 install scipy
$ sudo pip3 install tensorflow


Jupyter Notebook介绍、安装及使用教程

$ pip3 install --upgrade pip
$ pip3 install jupyter



[编辑] 2 Bytes to string


[编辑] 3 Basics

[编辑] 3.1 Numbers

Python 2.7.9 (default, Mar  1 2015, 12:57:24) 
>>> a = 3.23
>>> b = 4
>>> c = 52.3E-4
>>> print a, b, c
3.23 4 0.00523


[编辑] 3.2 HEX

>>> print str(254)
254
>>> print hex(254)
0xfe
>>> print hex(254).upper()
0XFE
>>> str = "%02X" %(254); print str
FE
>>> print hex(1023)
0x3ff
>>> print hex(1023)[0:-2]
0x3


[编辑] 3.3 Strings

#!/usr/bin/python

str_1 = 'Jack Tan'
str_2 = "Ga Xiao Duo"
str_3 = '''This is a multi-line string. first line.
second line'''

# using the startswith method of the string object
if str_1.startswith('Ja'):
    print("Yes, str_1 start with 'Ja'")

if 'a' in str_1:
    print('Yes, str_1 contains the string "a"')

substr = 'ac'
if str_1.find(substr) != -1:
    print('Yes, str_1 contains the string "{0}"'.format(substr))
    print('Yes, {0} contains the string "{1}"'.format('str_1', substr))
    print('Yes, {} contains the string "{}"'.format('str_1', substr))
    # using the format method of the string object

deli = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']

# using the join method of the string object
print(deli.join(mylist))

Output:

Yes, name start with 'Ja'
Yes, name contains the string "a"
Yes, name contains the string "ac"
Brazil_*_Russia_*_India_*_China

Once your have created a string, you cannot change it



[编辑] 3.4 Variable

Python refers to anything used in a program as an object.

Do not need type declaration of variable in python

Python 2.7.9 (default, Mar  1 2015, 12:57:24) 
>>> a = 3.1415
>>> b = 100000
>>> c = 'Jack Tan'
>>> d = ['x1', 'x2']
>>> print a, b, c, d
3.1415 100000 Jack Tan ['x1', 'x2']
.

Variables can hold values of different types called data types. The basic types are numbers and strings. We can create our own types using classes.


[编辑] 3.5 Indentation

Whitespace at the beginning of the line is important!

Spaces and tabs at the beginning of the logical line are used to determine the indentation level of the logical line, which in turn is used to determine the grouping of statements.

Statements which go together must have the same indentation. Each usch set of statements is called a block


[编辑] 3.6 Format

#!/usr/bin/python

#width = 10,precise = 3,align = left
print "PI = %10.3f" %(math.pi)

# don't add the '\n' at the end of line
print "PI = %10.3f" %(math.pi),

#width = 10,precise = 3,align = rigth
print "PI = %-10.3f" % math.pi


Output:

PI = 3.141593
PI =      3.142


Python 2.7.9 (default, Mar  1 2015, 12:57:24) 
>>> print "%.3s " % ("jcodeer") #precise = 3
jco 
>>> print "%.*s" % (4,"jcodeer") #precise = 4
jcod
>>> print "%10.3s" % ("jcodeer") #width = 10,precise = 3
       jco
>>>


fmat = "%r %r %r %r"
 
print fmat % (1, 2, 3, 4)
print fmat % ("one", "two", "three", "four")
print fmat % (True, False, False, True)
1 2 3 4
'one' 'two' 'three' 'four'
True False False True


print('{0:.3}'.format(0.3333333))
#print('{0:.3}'.format(1/3))
print('{0:_^11}'.format('Hello'))
print('{0:+^11}'.format('Hello'))
print('{name} wrote {book}'.format(name='Jack', book='Hello world'))
PI = 3.141593
PI =      3.142

0.333
___Hello___
+++Hello+++
Jack wrote Hello world



[编辑] 3.7 yield

类 return 作用,不过返回的是生成器,可以用 for ... in generator 或 next 遍历该生成器



[编辑] 4 Operators



[编辑] 5 Control Flow

[编辑] 5.1 if

i = 5
if i == 0:
    print 'Zero'
elif i > 0:
    print 'Positive'
else:
    print 'Negative'


[编辑] 5.2 While

n = 4
while n:
    print 'Loop is OK'
    n -= 1
else:
    print 'Loop is over'



[编辑] 5.3 For

for ... in

for i in range(1,5):
    print i
else:
    print 'The loop is over'



[编辑] 6 Functions



[编辑] 7 Data Structures

[编辑] 7.1 Dict


[编辑] 7.2 List

中括号 [] 声明


[编辑] 7.3 元组

括号声明,一旦定义 元素不可更改


[编辑] 8 Exceptions

[编辑] 8.1 with...as

#!/usr/bin/python

import sys

class test:
    def __enter__(self):
        print("enter")
        return 1
    def __exit__(self, *args):
        print("clean up")
        return False
        #return True


with test() as t:
    print("t is not the result of test(), it's __enter__ returned")
    print("t is 1, yes, it's {0}".format(t))
    print "t is 1, yes, it's", t
    raise NameError("Error")

sys.exit()
print("Never here")



[编辑] 9 Matplotlib


[编辑] 9.1 bar

def currency(x, pos):
    """The two args are the value and tick position"""
    if x >= 1e6:
        s = '${:1.1f}M'.format(x*1e-6)
    else:
        s = '${:1.0f}K'.format(x*1e-3)
    return s

formatter = FuncFormatter(currency)

fig, ax = plt.subplots(figsize=(6, 8))
ax.xaxis.set_major_formatter(formatter)


[编辑] 9.2 hist


[编辑] 10 Numpy

在 Python 中将 NumPy 数组保存为图像

import numpy as np
import matplotlib.pyplot as plt

ds = np.arange(0,737280, 1, np.uint8)
ds = np.reshape(ds, (1024, 720))

plt.imsave('test.jpg', ds)


[编辑] 11 Seaborn


[编辑] 11.1 Panel


[编辑] 12 Modules

[编辑] 12.1 Serial

import serial
import string
import binascii

s = serial.Serial('com4',9600)
s.open()

# rx data
n = s.inwaiting()
if n: 
    data = str(binascii.b2a_hex(s.read(n)))[2:-1]
    print(data)

# tx data
d = bytes.fromhex('10 11 12 34 3f') 
s.write(d)
s.close()


[编辑] 12.2 Struct (TX binary data)

import struct 

a = [0x00, 0x00, 0x00, 0x2c, 0x63, 0x00, 0x00, 0x00,  0x75, 0x4b, 0xef, 0x0f] 

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 

s.connect(('127.0.0.1',8000)) 

date = struct.pack("%dB"%(len(a)),*a) 

s.send(date) 



[编辑] 12.3 MQTT

Please refer to: http://wiki.jackslab.org/Noduino_OpenPlug#Turn_off_2


[编辑] 12.4 HTTP

httplib 实现了 http & https 的客户端协议,模块 urllib 和 urllib2 对 httplib 进行了更上层的封装

#!/usr/bin/env python
#  -*- coding:utf-8 -*-
 
import urllib2
import json
 
def http_post(url,data_json):
    jdata = json.dumps(data_json)
    req = urllib2.Request(url, jdata)
    response = urllib2.urlopen(req)
    return response.read()
 
url = 'http://192.168.0.100:8080/dev/test'
data_json = {'data' : '112233'}
resp = http_post(url,  data_json)
print(resp)


使用post方式时,数据放在 data 或者 body 中:

import urllib
import urllib2

test_data = {'ServiceCode':'aaaa','b':'bbbbb'}
test_data_urlencode = urllib.urlencode(test_data)
requrl = "http://192.168.1.16/dev/test"
req = urllib2.Request(url = requrl, data =test_data_urlencode)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res


Python3:

import urllib.request as http

resp = http.urlopen('http://iot.xxx.net')
# print(resp.info())
resp.read()
resp.close()

Reference: https://docs.python.org/3.8/library/urllib.request.html#module-urllib.request


[编辑] 13 CSV

import csv 
csvfile = open('data-text.csv', 'rb') 
reader = csv.reader(csvfile) 
for row in reader: 
    print row


[编辑] 13.1 Time


[编辑] 13.2 PDF

$ pip3 install pdfplumber

Refer to: https://zhuanlan.zhihu.com/p/40221732

import pdfplumber
import pandas as pd

pdf = pdfplumber.open('ncp-who.pdf')
page0 = pdf.pages[0]               #PDF 文件的第一页
table = page0.extract_table()
d = pd.DataFrame(table)

print(d.loc[0])
d.to_csv('ncp-who.csv', index = False, header = True, date_format='%Y%m%d')

复杂的,参考:https://github.com/jsvine/pdfplumber/blob/master/examples/notebooks/extract-table-nics.ipynb



[编辑] 14 getopt

[编辑] 14.1 sys

import sys
print(sys.argv[0])

for i in range(1, len(sys.argv)):
    print (i, sys.argv[i])
$ python test.py hello world
test.py
1 hello
2 world


[编辑] 14.2 getopt

import sys, getopt

opts, args = getopt.getopt(sys.argv[1:], "hi:o:")
input_file=""
output_file=""
for op, value in opts:
    if op == "-i":
        input_file = value
    elif op == "-o":
        output_file = value
    elif op == "-h":
        usage()
        sys.exit()

def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print ('test.py -i <inputfile> -o <outputfile>')
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print ('test.py -i <inputfile> -o <outputfile>')
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print ('Input file is "', inputfile)
   print ('Output file is "', outputfile)

if __name__ == "__main__":
   main(sys.argv[1:])


[编辑] 15 Resource









个人工具
名字空间

变换
操作
导航
工具箱