python第二天學習筆記


Python文件處理

文件內容替換

for line infileinput.input(“filepath”,inplace=1):

line=line.replace(“oldtest”,”newtest”)

print line,

 

//包含oldtest的替換成newtest

 

例子:

wangchao@wangchao-virtual-machine:~/python$vim finput.py

#!/usr/bin/env python

 

import fileinput

 

for line infileinput.input("contact_list.txt",backup='bak',inplace=1):

       line = line.replace('wang','chao')

       print line,

 

//將文件中wang改成chao,並將原文件備份一份bak文件

程序運行結果

wangchao@wangchao-virtual-machine:~/python$python finput.py

wangchao@wangchao-virtual-machine:~/python$ls

contact_list.txtbak

 

 

 

 

修改某行

with open(“foo.txt”,”r+”) as f:

old=f.read()#read everything in the file

f.seek()#rewind

f.write(“new line\n”+old)#write the new

line before

 

例子:

wangchao@wangchao-virtual-machine:~/python$vim fseek.py

#f = open('contact_list.txt','r+')

withopen('contact_list.txt',"r+") as f :

       old = f.read()

       f.seek(14)

       f.write("new line\n")

 

//f.seek(14),文件從第14個字符開始加newline,並換行

 

程序運行結果

wangchao@wangchao-virtual-machine:~/python$more contact_list.txt

1 cai  chengxnew    1885

2 ru  gongchengshi  1886

3 chao gongchengshi  1887

4 yao  chengxuyuan  1888

wangchao@wangchao-virtual-machine:~/python$python fseek.py

wangchao@wangchao-virtual-machine:~/python$more contact_list.txt

1 cai  chengxnew line

85

2 ru  gongchengshi  1886

3 chao gongchengshi  1887

4 yao  chengxuyuan  1888

 

 

 

 

wangchao@wangchao-virtual-machine:~$ vimtest.txt

wangchao@wangchao-virtual-machine:~/python$python

>>> f=file('test.txt')                 //打開只讀模式

>>> f=file('test.txt','w')              //打開可寫

>>> f.write('hello world!')            //寫入

>>> f.flush()                       //文件新建或被保存

 

 

>>> f.close()

>>> f=file('test.txt','a')

>>> f.write('AAA')                  //追加內存

 

wangchao@wangchao-virtual-machine:~/python$cat test.txt

hello world!AAA

 

 

 

 

 

 

python列表

處理和存放一組數據

用途:購物列表、工資列表……

語法:ShoppingList =[‘car’,’clothes’,’iphone’]

添加bookShoppingList列表:shoppingList.append(‘book’)

刪除car:          ShoppingList.remove(‘car’)

刪除最後一個:     ShoppingList.pop()

刪除列表中第二個內容:ShoppingList.pop(1)

 

wangchao@wangchao-virtual-machine:~/python$python

>>>nameList=['wang','cai','ru','yao']

>>> nameList

['wang', 'cai', 'ru', 'yao']

>>> nameList[2]               //取出2號,從0開始數

'ru'

>>> nameList[-1]               //取出最後一個

'yao'

>>> nameList.append('fei')       //加入fei

>>> nameList

['wang', 'cai', 'ru', 'yao', 'fei']

>>> nameList.insert(2,'sun')       //2號前插入sun

>>> nameList

['wang', 'cai', 'sun', 'ru', 'yao', 'fei']

 

>>> nameList.count('wang')       //統計wang出現的個數

1

 

>>> 'cai' in nameList          //判斷cai是否在列表中

True

 

>>> nameList

['wang', 'cai', 'sun', 'ru', 'yao', 'fei']

>>> nameList.index('fei')       //索引,fei在列表中的位置

5

 

>>> nameList.pop()           //刪除最後一個

'fei'

>>> nameList

['wang', 'cai', 'sun', 'ru', 'yao']

 

>>> nameList.remove('Y')         //刪除一個元素Y,如果其中有兩個Y,將只刪除前面一個

 

 

 

>>> nameList.reverse()           //排序

>>> nameList

['yao', 'ru', 'sun', 'cai', 'wang']

 

>>> nameList.reverse()           //排回

>>> nameList

['wang', 'cai', 'sun', 'ru', 'yao']

 

>>> nameList.sort()             //按字母排序

>>> nameList

['cai', 'ru', 'sun', 'wang', 'yao']

 

>>> nameList.extend('hello world')

>>> nameList

['cai', 'ru', 'sun', 'wang', 'yao', 'h','e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

>>> nameList[1]='ruru'                          //修改1號爲ruru

>>> nameList

['cai', 'ruru', 'sun', 'wang', 'yao', 'h','e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

>>> nameList.index('h')                         //查找h所在的位置

5

>>> i=nameList.index('h')

>>> nameList[i]='H'                              //h改成H

>>> nameList

['cai', 'ruru', 'sun', 'wang', 'yao', 'H','e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

 

 


 

 

元組

與列表一樣,但內容一旦生成,不可修改

NameList=(‘cai’,’ru’,’wang’)

遍歷列表

NameList=[‘cai’,’ru’,’wang’]

 

for name in NameList

         Print‘your name is’,name

 



 

列表練習程序

  1. 讓用戶輸入工資

  2. 輸出購物菜單及產品價格

  3. 計算用戶是否可支付

  4. 輸出用戶剩餘的錢,問用戶是否可繼續購物,如果選擇繼續,繼續進行,直到錢不夠爲止

 

 

 

補充:

>>> names="cai ru wang"         //定義一變量爲字符串

>>> names.split()                //將字符串分成一個列表

['cai', 'ru', 'wang']

>>> name_list=names.split()

>>> name_list                   //字符串被分成三段

['cai', 'ru', 'wang']

>>> name_list[1]                //取出ru

'ru'

 

 

 

F_choice=choice.strip()      //使choice脫去空格(多餘的)

 

 

 

 

參考程序:

wangchao@wangchao-virtual-machine:~/python$vim  mai.py

#!/usr/bin/python

 

import tab

import sys

products = ['Car','Iphone','Coffee','Mac','Cloths','Bicyle']

prices  = [250000,4999,    35,     9688, 438,     1500]

shop_list=[]

 

salary = int(raw_input('please input yoursalary:'))

 

while True:

     print "Things have in the shop.plesae choose one to buy:"

     for p in products:

         print p,'\t',prices[products.index(p)]

     choice = raw_input('Please input one item to buy:')

     F_choice = choice.strip()

     if F_choice in products:

           product_price_index = products.index(F_choice)

           product_price = prices[product_price_index]

           print F_choice,product_price

           if salary > product_price:

                  shop_list.append(F_choice)

                  print "Added %s intoyour shop list" % F_choice

                  salary = salary -product_price

                  print "Salaryleft:",salary

           else:

                  if salary < min(prices):

                        print 'Sorry,rest ofyour salary cannot buy anything! 88'

                        print "you havebought these things: %s" % shop_list

                        sys.exit()

                  else:

                        print "Sorry ,youcannot afford this product,please try other ones!"

 

 

 

程序運行結果:

wangchao@wangchao-virtual-machine:~/python$python mai.py

please input your salary:1536

Things have in the shop.plesae choose oneto buy:

Car    250000

Iphone 4999

Coffee 35

Mac    9688

Cloths 438

Bicyle 1500

Please input one item to buy:Car

Car 250000

Sorry ,you cannot afford thisproduct,please try other ones!

Things have in the shop.plesae choose oneto buy:

Car    250000

Iphone 4999

Coffee 35

Mac    9688

Cloths 438

Bicyle 1500

Please input one item to buy:Bicyle

Bicyle 1500

Added Bicyle into your shop list

Salary left: 36

Things have in the shop.plesae choose oneto buy:

Car    250000

Iphone 4999

Coffee 35

Mac    9688

Cloths 438

Bicyle 1500

Please input one item to buy:Bicyle

Bicyle 1500

Sorry ,you cannot afford thisproduct,please try other ones!

Things have in the shop.plesae choose oneto buy:

Car    250000

Iphone 4999

Coffee 35

Mac    9688

Cloths 438

Bicyle 1500

Please input one item to buy:Coffee

Coffee 35

Added Coffee into your shop list

Salary left: 1

Things have in the shop.plesae choose oneto buy:

Car    250000

Iphone 4999

Coffee 35

Mac    9688

Cloths 438

Bicyle 1500

Please input one item to buy:Coffee

Coffee 35

Sorry,rest of your salary cannot buyanything! 88

you have bought these things: ['Bicyle','Coffee']

wangchao@wangchao-virtual-machine:~/python$

 

 

 

 

 

 

 

 

Python字典講解與練習

python字典

語法:

                   DicName={

                                     “key1”: “value”,

                                     “key2”: “value 2”

 

                   Contacs={

                                     ‘wang’: ‘1886’,

                                     ‘cai’: ‘1887’,

                                     ‘ru’: ‘1888’,

                                     }

 

將之前寫的購物菜單用字典寫:

>>> product_dir={'car':250000,'Iphone':4999,'coffee':35,'Bicycle':1500}   

>>> product_dir                                      //查看菜單

{'car': 250000, 'coffee': 35, 'Bicycle':1500, 'Iphone': 4999}

>>> product_dir['coffee']                               //查價格

35

>>> product_dir.keys()                                //key

['car', 'coffee', 'Bicycle', 'Iphone']

>>> product_dir.values()                             //values

[250000, 35, 1500, 4999]

>>> product_dir.items()                                 //查相對應的

[('car', 250000), ('coffee', 35),('Bicycle', 1500), ('Iphone', 4999)]

 

 

>>> for i in product_dir:                    //打印product_dir

...  print i

...

car

coffee

Bicycle

Iphone

 

>>> product_dir.items()

[('car', 250000), ('coffee', 35),('Bicycle', 1500), ('Iphone', 4999)]

>>> for p,price in  product_dir.items():                        //打印items()

...  print p,price

...

car 250000

coffee 35

Bicycle 1500

Iphone 4999

 

字典查看、添加、刪除、修改

語法:

                   Contacs={

                                     ‘wang’:’1886’,

                                     ‘cai’:’1887’;

                                     ‘ru’:’1888’}

查看key:          Contacts.key()

查看value:      Contacts.values()

添加新item到字典:   Contacts[‘yao’]=’1889’

刪除item:        Contacts.popitem()                //默認刪除第一個

 

 

>>> product_dir

{'car': 250000, 'coffee': 35, 'Bicycle':1500, 'Iphone': 4999}

>>>product_dir.has_key('car')                       //判斷car是否存在

True

>>> product_dir.popitem()                         //刪除第一個

('car', 250000)

>>> product_dir

{'coffee': 35, 'Bicycle': 1500, 'Iphone':4999}

 

 

 

 

 

 

練習小程序:員工信息表

1.創建公司員工信息表,員工號、姓名、職位、手機

2.提供查找接口,通過員工姓名查詢用戶信息

 

 

 

參考程序:

wangchao@wangchao-virtual-machine:~/python$cat contact_list.txt

1 cai  chengxuyuan  1885

2 ru  gongchengshi  1886

3 chao gongchengshi  1887

4 yao  chengxuyuan  1888

 

 

wangchao@wangchao-virtual-machine:~/python$vim contact_dir.py

#!/usr/bin/python

import tab

contact_file = 'contact_list.txt'

f = file(contact_file)

contact_dic = {}

for line in f.readlines():

       name = line.split()[1]

       contact_dic[name] = line

 

'''

for n,v in contact_dic.items():

       print "%s \t%s" %(n,v),

 

'''

while True:

       input = raw_input("Please input the staff name:").strip()

       if len(input) == 0:continue

       if contact_dic.has_key(input):

                print "\033[32.1m%s\033[0m" % contact_dic[input]

       else:

                print 'Sorry,no staff namefound!'

 

程序運行結果:

wangchao@wangchao-virtual-machine:~/python$python contact_dir.py

Please input the staff name:zhou

Sorry,no staff name found!

Please input the staff name:cai

1 cai  chengxuyuan  1885

 

Please input the staff name:chao

3 chao gongchengshi  1887

 

Please input the staff name:yao

4 yao  chengxuyuan  1888

 

Please input the staff name:ru

2 ru  gongchengshi  1886

 

Please input the staff name:

 

 

 

 

 

Python函數

函數是在程序中將一組用特定的格式包裝起,定義一個名稱,然後可以在程序的任何地方通過調用此函數名來執行函數裏的那組命令

 

使用函數的好處:

程序可擴展性

減少程序代碼

方便程序架構的更改

 

定義函數

def sayHi():

         print“hello,world!”

 

def sayHi2(name):

         print“hello,%s,howare you?” %name

n=’wang’

sayHi2(n)

 

>>>sayHi(n)

Hello,wang,how are you?

 

 

小試牛刀1:

wangchao@wangchao-virtual-machine:~/python$vim function1.py

#!/usr/bin/env python

 

def sayHi(n):

       print "Hello %s,how are you?" % n

name = 'wang'

sayHi(name)

 

wangchao@wangchao-virtual-machine:~/python$python function1.py

Hello wang,how are you?

 

小試牛刀2:

wangchao@wangchao-virtual-machine:~/python$more contact_list.txt

1  cai  chengxuyuan 1885

2 ru  gongchengshi  1886

3 chao gongchengshi  1887

4 yao  chengxuyuan  1888

將名字取出,一個一個問hello XXX,how are you

 

 

 

參考:

wangchao@wangchao-virtual-machine:~/python$vim function2.py

#!/usr/bin/python

 

def sayHi(n):

       print "hello %s,how are you?" %n

contact_file ='contact_list.txt'

 

f = file(contact_file)

for line in f.readlines():

       name = line.split()[1]

       sayHi(name)

 

 

程序結果:

wangchao@wangchao-virtual-machine:~/python$python function2.py

hello cai,how are you?

hello ru,how are you?

hello chao,how are you?

hello yao,how are you?

 

 

 

 

函數參數

def info(name,age):

         print“Name:%s Age:%s” %(name,age)

 

 

 

 

綜合練習:

寫一個atm程序,功能要求:

  1. 額度15000

  2. 可以提現,手續費5%

  3. 每月最後一天出賬單(每月30天)

  4. 記錄每月日常消費流水

  5. 提供還款接口

優化(可選):

1.每月10號爲還款日,過期未還,按欠款額5%計息

 

 

 

 

輸出類似:

本期還款總額: XX

交易日       交易摘要    交易金額   計息

XX            XX         XX          XX

 

 

補充:Pickle()#、函數默認參數、關鍵參數可學習一下,寫程序可更加便捷

 

 

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章