Python_2(form19)

previous:Python

 

--------------------------------------------------------------------------------------------

- 19 - My trip to Walmart and Sets

Sets : 1,in curve brace {} ,2 have no duplicate 

groceries = {'beer', 'cereal','milk','apple', 'avacodo', 'beer'}
print(groceries, groceries.__len__())

if 'cereal' in groceries:
    print('We have got milk')
C:\Users\30478\AppData\Local\Programs\Python\Python36\python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/func1.py
{'beer', 'avacodo', 'cereal', 'milk', 'apple'} 5
We have got milk

Process finished with exit code 0

 ----20 - Dictionary ------------------------------------------------------------------------------------------------

a dictionary in python is a Key Value pair.

classmates = {'Tony': "iron man", 'Emma': "pretty girl", 'Charles': "ProfessorX", 'Rogen':"Wolf"}
#print(classmates)
#print(classmates['Tony'])
for x, y in classmates.items():
    print(x+" is "+y)
C:\Users\30478\AppData\Local\Programs\Python\Python36\python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/func1.py
Tony is iron man
Emma is pretty girl
Charles is ProfessorX
Rogen is Wolf

Process finished with exit code 0

----21 - Modules ------------------------------------------------------------------------------------------------

Modules:a set of a bounch of function.

usage of Modules:import module

module:feel.py

feel.py

def tsushi(fish):
    print(fish+" can be used to cook Tsushi")

 

func1.py

import feel
import random
feel.tsushi("tuna")
x = random.randrange(1, 100)
print(x)
C:\Users\30478\AppData\Local\Programs\Python\Python36\python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/func1.py
tuna can be used to cook Tsushi
19

Process finished with exit code 0

 

 

 ----22 - Download an Image from the Web ------------------------------------------------------------------------------------------------

IDE: JetBrains PyCharm Community Edition 2017.2 x64:

file-setting - project Name( chose the one you want to use)-project interpreter :

1) on the right ,is   downloaded modules form web

2) + ,install module(downloaded),could select 

3) - ,uninstall  module

 

 

use random to generate a random number as a img name

use urllib.request  to download

image will be download,and stored in project folder.

 

import random
import urllib.request

def download_webImage(url):
    name = random.randrange(1,1000)
    #str(number) convert a number to string
    full_name = str(name) + ".jpg"
    urllib.request.urlretrieve(url, full_name)

download_webImage("https://gss1.bdstatic.com/-vo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike180%2C5%2C5%2C180%2C60/sign=220dd86ab48f8c54f7decd7d5b404690/960a304e251f95ca5c948c32c9177f3e660952d4.jpg")

 

 

 ----23 - How to Read and Write Files ------------------------------------------------------------------------------------------------

fw = open('stamp.txt', 'w')
fw.write('this syntx well first create a new file named stamp.txt \n')
fw.write('Try write something into a file \n')
fw.close()

fr = open('C:/Users/30478/Desktop/stamp.txt', 'r')
text = fr.read()
print(text)
fr.close()
C:\Users\30478\AppData\Local\Programs\Python\Python36\python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/main.py
this syntx well first create a new file named stamp.txt 
Try write something into a file 
sky

Process finished with exit code 0

C:\Users\30478\Desktop\stamp.txt

this syntx well first create a new file named stamp.txt 
Try write something into a file 
sky

 

 

 ----24 - Downloading Files from the Web ------------------------------------------------------------------------------------------------

python目录前加一个r:r是保持字符串原始值的意思,就是说不对其中的符号进行转义。因为windows下的目录字符串中通常有斜杠"\",
而斜杠在Python的字符串中有转义的作用。例如:\n表示换行如果路径中有\new就会被转义。加上r就是为了避免这种情况。
from urllib import request

goog_url = "https://query1.finance.yahoo.com/v7/finance/download/GOOG?period1=1500721097&period2=1503399497&interval=1d&events=history&crumb=EoXe3TOhKsy"

def download(csv_url):
    response = request.urlopen(csv_url)
    csv = response.read()
    csv_str = str(csv)
    lines = csv_str.split("\\n")
    filename = r"goog.csv"
    fw = open(filename, "w")
    for line in lines:
        fw.write(line+'\n')
    fw.close()

download(goog_url)

 

 ----Tutorial - 25-27 - How to Build a Web Crawler (3/3) -----------------------------------------------------------------------------------------------

import requests
from bs4 import BeautifulSoup

def trade_spider(max_pages):
    page = 1
    while page <= max_pages:
        url = "https://www.incnjp.com/forum.php?mod=forumdisplay&fid=591&filter=sortid&sortid=6&searchsort=1&goods_type=5&goods_area=2" \
              "&page=" + str(page)
        print(url)
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text, "html.parser")
        #for link in soup.find_all('a', {'class': 'item-name'}):
        for link in soup.find_all('a'):
            href = link.get('href')
            #print(href)
            if href is None:
                break
            print(href[0: 6])
            print("!!!" + href[0: 6] is 'thread')
            #if href[0: 6] is 'thread': is variable the same memory,== value is same
            if href[0: 6] == 'thread':
                print(href[0: 6])
                print("!!!" + href)
                get_single_item_data("https://www.incnjp.com/" + href)
        page += 1

def get_single_item_data(item_url):
    sourse_code = requests.get(item_url)
    plain_text = sourse_code.text
    soup = BeautifulSoup(plain_text)
    for item_name in soup.findAll('span', {'id': 'thread_subject'}):
        print(item_name.string)

trade_spider(1)

 ---- 28 - You are the only Exception ------------------------------------------------------------------------------------------------

def x1():
    tuna = int(input("input a number:\n"))
    print(tuna)

def xxx():
    # go loop until get a number input
    while True:
        try:
            number = int(input("input a number:\n"))
            print(18/number)
            break
        #excpetion
        except ValueError:
            print("Make sure enter a number")
        except ZeroDivisionError:
            print("Don't pick zero")
        #general exception
        except:
            break
        #try - except - finally(always executed )
        finally:
            print("Input is over.")
xxx()

 

C:\Users\30478\AppData\Local\Programs\Python\Python36\python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/testErrorAndExceptoin.py
input a number:
x
Make sure enter a number
Input is over.
input a number:
x
Make sure enter a number
Input is over.
input a number:
0
Don't pick zero
Input is over.
input a number:

7
Make sure enter a number
Input is over.
input a number:
2.5714285714285716
Input is over.

Process finished with exit code 0

 

 

 ----29 - Classes and Objects------------------------------------------------------------------------------------------------

class Enemy:
    life = 3
    def attact(self):
        print("It's painful!")
        self.life -= 1

    def checkLife(self):
        if self.life <= 0:
            print('Game Over!')
        else:
            print(str(self.life) + "life left")

#use class by made object  ,ememy1 is a object of ememy class
ememy1 = Enemy()
ememy2 = Enemy()

ememy1.attact()
ememy1.attact()
ememy2.attact()
ememy1.checkLife()
ememy2.checkLife()
C:\Users\30478\AppData\Local\Programs\Python\Python36\python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/classAndObject.py
It's painful!
It's painful!
It's painful!
1life left
2life left

Process finished with exit code 0

 

 

 

 ----30 - init ------------------------------------------------------------------------------------------------

class tuna:

    def __init__(self):
        print("Game start!")

    def checkLife(self, si):
        print(si)
#use class by made object
ememy1 = tuna()
ememy1.checkLife("sssss ssss")

class Enemy:
    def __init__(self,x):
        self.energy = x
    def get_energy(self):
        print(self.energy)

json = Enemy(10)
andy = Enemy(90)
json.get_energy()
andy.get_energy()
C:\Users\30478\AppData\Local\Programs\Python\Python36\python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/classAndObject.py
Game start!
sssss ssss
10
90

Process finished with exit code 0

 

 

  ----31 - Class vs Instance Variables------------------------------------------------------------------------------------------------

class girl:
    gender = "girl"
    def __init__(self, name):
        self.name = name

ammy = girl("ammy")
anna = girl("anna")
#gender is a class variable,name is a instance variable
print(ammy.name + " is a " + ammy.gender)
print(anna.name + " is a " + anna.gender)

 

C:\Users\30478\AppData\Local\Programs\Python\Python36\python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/classAndObject.py
ammy is a girl
anna is a girl

Process finished with exit code 0

 

  ----32 - Inheritance------------------------------------------------------------------------------------------------

class Parent():
    def print_last_name(self):
        print("Robert")
    def print_middle_name(self):
        print("alean")
class Child(Parent):
    def print_first_name(self):
        print("Charly")
#overwrite
    def print_middle_name(self):
        print("Blue")

charly = Child()
charly.print_first_name()
charly.print_middle_name()
charly.print_last_name()
C:\Users\30478\AppData\Local\Programs\Python\Python36\python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/parent.py
Charly
Blue
Robert

Process finished with exit code 0

 inherit a class  from other  python file

 

parent.py

class Parent:
    def print_last_name(self):
        print("Robert")
    def print_middle_name(self):
        print("alean")
import parent
class Child(parent.Parent):
    def print_first_name(self):
        print("Charly")
#overwrite
    def print_middle_name(self):
        print("Blue")

charly = Child()
charly.print_first_name()
charly.print_middle_name()
charly.print_last_name()
C:\Users\30478\AppData\Local\Programs\Python\Python36\python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/children.py
Charly
Blue
Robert

Process finished with exit code 0

 

 

  ----33 - Multiple Inheritance------------------------------------------------------------------------------------------

 parent.py

class Parent():
    def print_last_name(self):
        print("Robert")
    def print_middle_name(self):
        print("alean")

class Study():
    def object1(self):
        print("I am good at math")

children.py

import parent

#pass :in class need a line of code ,but not want do anything,just write pass,fix the syntxerror
class Child(parent.Parent, parent.Study):
    pass
charly = Child()

charly.print_middle_name()
charly.print_last_name()
charly.object1()

console

C:\Users\30478\AppData\Local\Programs\Python\Python36\python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/children.py
alean
Robert
I am good at math

Process finished with exit code 0

 

  ----34 - threading-----------------------------------------------------------------------------------------------

 

import threading
class Clcthread(threading.Thread):
    #if we don't want to use variable just put  a '_' over there
    def run(self):
        for _ in range(10):
            print('Loop for 10 times' + threading.current_thread().getName())

x = Clcthread(name="Run thread 1")
y = Clcthread(name="Run thread 2")
x.start()
y.start()
C:\Users\30478\AppData\Local\Programs\Python\Python36\python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/threadingtest.py
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 2

Process finished with exit code 0

 

 

  ----38 - Unpack List or Tuples------------------------------------------------------------------------------------------------

 Tuples 数组

package =['December 25', '2017', '2000']
date, year, price = package
print(date)

#python cookbook

def drop_first_last(grades):
    first, *middle, last = grades
    avg = sum(middle)/len(middle)
    print(len(middle), "students", avg,  "on avg score")

drop_first_last([65, 76, 88, 91, 98, 100])

 first, *middle, last = sorted(grades) it drops minimum and maximum values.

C:\Users\30478\AppData\Local\Programs\Python\Python36\python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/Unpack.py
December 25
4 students 88.25 on avg score

Process finished with exit code 0

 ----Python Programming Tutorial - 40 - Lamdba -----------------------------

#lambda: small function without name.
answer = lambda x: x*7
print(answer(5))
C:\Users\30478\AppData\Local\Programs\Python\Python36\python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/lambdatest.py
35

Process finished with exit code 0

 

转载于:https://www.cnblogs.com/charles999/p/7397961.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是一段python代码,请根据这段代码基于python_opencv实现点击self.pushButton时打开已搜到的相机列表并实现鼠标点击选择打开相应相机并显示在self.label,当点击self.pushButton_2时抓取当时帧显示在self.label_2 from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(1044, 729) self.gridLayoutWidget = QtWidgets.QWidget(Form) self.gridLayoutWidget.setGeometry(QtCore.QRect(19, 9, 991, 551)) self.gridLayoutWidget.setObjectName("gridLayoutWidget") self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setObjectName("gridLayout") self.label = QtWidgets.QLabel(self.gridLayoutWidget) font = QtGui.QFont() font.setFamily("Adobe Arabic") font.setPointSize(26) self.label.setFont(font) self.label.setStyleSheet("background-color: rgb(255, 255, 127);") self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.gridLayout.addWidget(self.label, 0, 0, 1, 1) self.label_2 = QtWidgets.QLabel(self.gridLayoutWidget) font = QtGui.QFont() font.setFamily("Adobe Arabic") font.setPointSize(26) self.label_2.setFont(font) self.label_2.setStyleSheet("background-color: rgb(170, 255, 255);") self.label_2.setAlignment(QtCore.Qt.AlignCenter) self.label_2.setObjectName("label_2") self.gridLayout.addWidget(self.label_2, 0, 1, 1, 1) self.pushButton = QtWidgets.QPushButton(Form) self.pushButton.setGeometry(QtCore.QRect(130, 640, 161, 51)) font = QtGui.QFont() font.setFamily("Adobe Arabic") font.setPointSize(18) self.pushButton.setFont(font) self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(Form) self.pushButton_2.setGeometry(QtCore.QRect(660, 640, 161, 51)) font = QtGui.QFont() font.setFamily("Adobe Arabic") font.setPointSize(18) self.pushButton_2.setFont(font) self.pushButton_2.setObjectName("pushButton_2") self.retranslateUi(Form) self.pushButton.clicked.connect(Form.Action) # type: ignore self.pushButton_2.clicked.connect(Form.UserNow) # type: ignore QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.label.setText(_translate("Form", "实时图像")) self.label_2.setText(_translate("Form", "抓取图像")) self.pushButton.setText(_translate("Form", "打开相机")) self.pushButton_2.setText(_translate("Form", "抓取图像"))
05-18

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值