跳到主要內容

發表文章

目前顯示的是有「Python」標籤的文章


Python-開啟檔案-png

Python 開啟檔案 pypng 安裝: linux、mac :pip3 install pypng windows    :之後補上 程式碼說明 寫入 import png f = open('ramp.png', 'wb') w = png.Writer(255, 5, greyscale=True) w.write(f, [range(256) , range(256) ,range(256) ,range(256) ,range(256) ]) f.close() 讀取 import png import urllib r=png.Reader(file=urllib.request.urlopen('http://www.schaik.com/pngsuite/basn0g02.png')) r.read()

Python-開啟檔案-excel

Python 開啟檔案 excel 安裝: linux、mac :pip3 install openpyxl、pip3 install xlwt、pip3 install xlrd windows    :之後補上 程式碼說明 2007年版後 寫入 from openpyxl import Workbook,load_workbook wb = Workbook() ws = wb.active ws1 = wb.create_sheet('Mysheet') ws2 = wb.create_sheet('Mysheet', 0) ws1.title = 'New Title' print(wb.sheetnames) ws['A4'] = 4 ws.cell(row=4, column=2, value=10) wb.save('demo.xlsx')  讀取 wb_load = load_workbook('demo.xlsx')  sheet_ranges = wb_load['Sheet'] print(sheet_ranges['A4'].value) 2007年版前 寫入 import xlwt from datetime import datetime style0 = xlwt.easyxf('font: name Times New Roman, \ color-index red, bold on',num_format_str='#,##0.00') style1 = xlwt.easyxf(num_format_str='D-MMM-YY') wb = xlwt.Workbook() ws = wb.add_sheet('A Test Sheet') ws.write(0, 0, 124, style0) ws.write(1, 0, datetime.now(), sty...

Python-資料庫-mongodb-pymongo

Python 資料庫 mongodb-pymongo 安裝: linux、mac:pip3 install pymongo windows: import pymongo client = pymongo.MongoClient("mongodb://localhost:27017/") db = client['demo_db'] col = db['demo_col'] dict1 = { "name": "ab123ab456g", "day": "1890-04-05" } result = col.insert_one(dict1)  dict2 = [   { "name": "ki", "day": "1666-1-1"},   { "name": "aa", "day": "1222-11-11"},   { "name": "gg-gg", "day": "1333-02-22"},   { "name": "T-T", "day": "1444-03-02"},   { "name": "f-f", "day": "1555-01-01"} ] result = col.insert_many(dict2) result = col.find_one() print(result) results = col.find() for result in col.find(): print(result) results = col.find() query = {'...

Python-資料庫-mysql-sqlalchemy

Python 資料庫 mysql-sqlalchemy 安裝 Linux、mac : pip3 install SQLAlchemy windows     :之後補充 第一部分 from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///:memory', echo=False) Base = declarative_base() Session = sessionmaker(bind=engine) 第二部分 from test_sqlalchemy import * from sqlalchemy import Column, Integer, String class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) password = Column(String) def __repr(self): return "<User(name={})>".format(self.name) 第三部分 from test_sqlalchemy import * from build_model import * Base.metadata.create_all(engine) user1 = User(name='user1', fullname='user1', password='user1') user2 = User(name='user2', fullname='user2...

Python-資料庫-mysql-pymysql

Python 資料庫 mysql-pymysql 安裝: linux、mac:pip3 install PyMySql windows    : 之後補充 import pymysql.cursors connection = pymysql.connect(host='ip', user='root', password='password', db='database_name',charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) #    CREATE TABLE `users` ( #    `id` int(11) NOT NULL AUTO_INCREMENT, #    `email` varchar(255) COLLATE utf8_bin NOT NULL, #    `password` varchar(255) COLLATE utf8_bin NOT NULL, #    PRIMARY KEY (`id`) #) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin #AUTO_INCREMENT=1 ; with connection.cursor() as cursor:     sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"     cursor.execute(sql, ('ab123ab456g@example.com', 'very-secret')) connection.commit() with connection.cursor() as cursor:     sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"     cursor.execute(sql, ('ab123ab456g@exa...

Python-設計模式-拜訪模式

Python 設計模式 拜訪模式 from abc import ABCMeta, abstractmethod NOT_IMPLEMENTED = "You should implement this." class CarElement:     __metaclass__ = ABCMeta     @abstractmethod     def accept(self, visitor):         raise NotImplementedError(NOT_IMPLEMENTED) class Body(CarElement):     def accept(self, visitor):         visitor.visitBody(self) class Engine(CarElement):     def accept(self, visitor):         visitor.visitEngine(self) class Wheel(CarElement):     def __init__(self, name):         self.name = name     def accept(self, visitor):         visitor.visitWheel(self) class Car(CarElement):     def __init__(self):         self.elements = [             Wheel("front left"), Wheel("front right"),           ...

Python-設計模式-解譯器模式

Python 設計模式 解譯器模式 class Expression: def interpret(self, context): pass class TerminalExpresssion(Expression): def __init__(self): self.data = '' def terminalExpreession(self, data): self.data = data def interpret(self, context): if self.data in context: return True return False class AddExpression(Expression): def __init__(self): self.expr1 = '' self.expr2 = '' def addExpreession(self, expr1, expr2): self.expr1 = expr1 self.expr2 = expr2 def interpret(self, context): return self.expr1.interpret(context) and expr2.interpret(context) class OrExpression(Expression): def orExpreession(self, expr1, expr2): self.expr1 = expr1 self.expr2 = expr2 def interpret(self, context): return self.expr1.interpret(context) or expr2.interpret(context) T1 = TerminalExpresssion() T2 = TerminalExpresssion() T1.terminalExpreession('Name1') T2.terminalExpreession('Human') A1 = OrExpression() A...

Python-設計模式-備忘錄模式

Python 設計模式 備忘錄模式 class Memento:     def __init__(self, state):        self.state = state     def GetState(self):        return self.state  class Origniator:     def __init__(self):        self.state = ''     def GetState(self):        return self.state     def SetState(self, state):        self.state = state     def SaveStateToMemeto(self):        return Memento(self.state)     def getStateFromMemeto(self, Memento):        self.state = Memento.GetState()  class CareTaker:     def __init__(self):        self. MementoList = []     def Add(self, memento):        self.MementoList.append(memento)     def GetMementoIndex(self, ind...

Python-設計模式-狀態模式

Python 設計模式 狀態模式 class A:     def __init__(self):        self.State = ''     def SetState(self, state):        self.State = state     def GetState(self):        return self.State  class State:     def ChangeState(self, obj):        pass class StartState(State):     def ChangeState(self, obj):        print('setting Start State')        obj.SetState('Start')  class EndState(State):     def ChangeState(self, obj):        print('setting End State')        obj.SetState('End')  a = A()  S = StartState()  S.ChangeState(a)  print(a.GetState())  E = EndState()  E.ChangeState(a)  print(a.GetState()) 程式碼說明 定義要被改變狀態的類別,定義state介面,定義改變狀態類別。設定物件、改變狀態。

python-設計模式-觀察器模式

python 設計模式 觀察器模式 class Subject:     def __init__(self):        self.State = ''        self.OList = []     def GetState(self):        return self.State     def SetState(self, state):        self.State = state        self.NotifyObeservers()     def AddObeserver(self,observer):        self.OList.append(observer)     def RemoveObeserver(self,observer):        self.OList.remove(observer)     def NotifyObeservers(self):        for O in self.OList:           O.Update()  class Observer:     def __init__(self,name,subject):        self.name = name        self.Subject = subject     def Update(self):      ...

python-設計模式-迭代器模式

python 設計模式 迭代器模式 class Item:    def __init__(self, name, price):       self.name = name        self.price = price     def __str__(self):        return "{}: $ {}".format(self.name, self.price)  class MenuIterator:     def __init__(self, items):        self.indx = 0        self.items = items     def has_next(self):        return False if self.indx >= len(self.items) else True      def next(self):        item = self.items[self.indx] self.indx += 1 return item      def remove(self):        return self.items.pop()  class Menu:      def __init__(self):         self.items = []      def add(self, item):         self.items.app...

Python-設計模式-命令模式

Python 設計模式 命令模式 class Cook:     def cook(self, food):        print('cook ' + food)  class Invoke:     def __init__(self):        self.CommandList = []     def AddOrder(self, command):        self.CommandList.append(command)     def CancelOrder(self, command):        self.CommandList.remove(Command)     def SendOrder(self):        for i in self.CommandList:           i.excute()           self.CommandList.clear()  class Command:     def excute(self):        pass  class CreateCommand1:     def __init__(self):        self.cook = None        self.food = 'pig'     def SetCook(self,cook):       ...

Python-設計模式-責任鏈模式

Python 設計模式 責任鏈模式 class buySomething:    def __init__(self):        self.Money = 0     def SetPrice(self, Money):        self.Money = Money     def SendRequest(self, handler):        handler.OktoBuy(self.Money)  class Handler:     def __init__(self):        self.Level = None     def OktoBuy(self):        pass     def SetNextLevelHandler(self, level):        self.Level = level  class BuyItLevel1(Handler):     def OktoBuy(self, request):        if 0<=request<=50:           print('Level 1 Ok buy')        else:           self.Level.OktoBuy(request)  class BuyItLevel2(Handler):     def OktoBuy(self, request): ...

python-設計模式-策略模式

python 設計模式 策略模式 class Stragey:     def Algorithm(self):        pass class  Stragey1(Stragey):     def Algorithm(self):        print('run algorithm1')  class Stragey2(Stragey):     def Algorithm(self):        print('run algorithm2')  class A:     def __init__(self):        self.a = None     def SetAlgorithm(self, algorithm):        self.a = algorithm a = A() a.SetAlgorithm(Stragey1())  a.a.Algorithm()  a.SetAlgorithm(Stragey2())  a.a.Algorithm()  程式碼說明 定義策略模式,寫策略一、策略二類別,定義類別A,並設定可以存放不同策略之函數,執行上述功能。

Python-設計模式-中介者模式

Python 設計模式 中介者模式 class ChatRoom:       def __init__(self):          self.UserList = []        def showMessage(self, User, Message):           pass        def Registor(self, User):           self.UserList.append(User)       def UnRegistor(self, User):           self.UserList.remove(User)  class CreateChatRoom(ChatRoom):        def showMessage(self, User, Message):           if User in self.UserList:               print(User.UserName,Message)           else: print('User Not in System')  class User:        def __init__(self):           self.UserName = ''           self.Medi...

python-設計模式-template

python 設計模式 template class Car:     def Drive(self):        pass     def Start(self):        pass     def Stop(self):        pass     def Run(self):        pass  class BMW(Car):     def Drive(self):        print('BMW is Driving')     def Start(self):        print('BMW is starting')     def Stop(self):        print('BMW is Stop')     def Run(self):        self.Start()        self.Drive()        self.Stop()  class Toyota(Car):     def Drive(self):        print('Toyota is Driving')     def Start(self):        print('Toyota is starting')     def Stop(s...

python-設計模式-裝飾模式

python 設計模式 裝飾模式 class Hamberger:     def __init__(self):        self.price = 0        self.meat = ''     def GetPrice(self):        print(self.price)  class PigHamberger(Hamberger):     def __init__(self):        self.price = 35        self.meat = 'Pig'  class BeefHamberger(Hamberger):      def __init__(self):         self.price = 45         self.meat = 'Beef'  class Decorator(Hamberger):      def __init__(self, hamberger):         self.price = hamberger.price         self.meat = hamberger.meat  class EggDecorator(Decorator):     def __init__(self,hamberger):         super().__init__(hamberger)      def GetPrice(self):...

Python-設計模式-門面模式

Python 設計模式 門面模式 class Sub_A:     def Start_A_Part(self):        print('A Part Start')     def Stop_A_Part(self):        print('A Part Stop')  class Sub_B:     def Start_B_Part(self):        print('B Part Start')     def Stop_B_Part(self):        print('B Part Stop')  class Sub_C:     def Start_C_Part(self):        print('C Part Start')     def Stop_C_Part(self):        print('C Part Stop')  class System:     def __init__(self):        self.A = Sub_A()        self.B = Sub_B()        self.C = Sub_C()     def start_system(self):        self.A.Start_A_Part()        self.B.Start_B_Part()      ...

Python-設計模式-共享模式

Python 設計模式 共享模式 class Font:     def __init__(self):        self.Size = 0        self.Type = ''     def printAll(self):        print(self.Size, self.Type)  class FontFacotry:     def Word(self, Size=3, Type='1'):        F = Font()        F.Size = Size        F.Type = Type        return F  FontSize = [1,2,3] FontType = ['1','2','3'] Facotry = FontFacotry()  F1 = Facotry.Word(FontSize[0],FontType[0])  F1.printAll()  F2 = Facotry.Word( FontSize[1],FontType[1] ) F2.printAll()  F3 = Facotry.Word( FontSize[2],FontType[2] ) F3.printAll() 程式碼說明 font 定義類別 fontFacotry物件生成工廠 fontsize用來儲存font大小的外部空間 fonttype用來儲存font種類的外部空間