廣告

顯示具有 python 標籤的文章。 顯示所有文章
顯示具有 python 標籤的文章。 顯示所有文章

2015年3月7日 星期六

[python] FILE I/O (read) & to Dictionary | FILE I/O (write) & input(raw_input)


readFile.py
import pickle
#save object type

file = open('people.txt','r')
print 'the content is ',file.name

people = {}

for line in file.readlines():
   print 'read line:',line
   #rstrip = remove '\n'
   part = line.rstrip().split(' ')
   people[part[1]] = part



print people

print '=========use pickle======'

file.close()

pick = open('picktest.txt','w')
pickle.dump(people,pick)
pick.close

pick = open('picktest.txt')
people = pickle.load(pick)
print(people)


consol
the content is  people.txt
read line: 1 lewis 183 70

read line: 2 leo 175 80

read line: 3 jim 170 60

read line: 4 7 170 80

read line: 5 fai 180 70

{'lewis': ['1', 'lewis', '183', '70'], 'fai': ['5', 'fai', '180', '70'], 'jim': ['3', 'jim', '170', '60'], '7': ['4', '7', '170', '80'], 'leo': ['2', 'leo', '175', '80']}
=========use pickle======
{'jim': ['3', 'jim', '170', '60'], 'lewis': ['1', 'lewis', '183', '70'], 'fai': ['5', 'fai', '180', '70'], '7': ['4', '7', '170', '80'], 'leo': ['2', 'leo', '175', '80']}


people.txt

1 lewis 183 70
2 leo 175 80
3 jim 170 60
4 7 170 80
5 fai 180 70


writeFile.py
#inpput can't get blank

count = input("input how many people:")

list = []

for x in range(count):
        print 'input number name height weight,splite by blank'
        a = raw_input("-->:")
        list.append(a)


print 'your input is ' ,list


f = open('people2.txt','w')
for x in list:
        f.write(x+"\n")

f.close()

consol

([pythonTutorai])lewis@lewis-virtual-machine:~/pythonTutorial/tutorial2$ python writeFile.py
input how many people:3
input number name height weight,splite by blank
-->:6 aa 134 11
input number name height weight,splite by blank
-->:7 bb 431 233
input number name height weight,splite by blank
-->:8 cc 167 70
your input is  ['6 aa 134 11', '7 bb 431 233', '8 cc 167 70']

people2.txt
6 aa 134 11
7 bb 431 233
8 cc 167 70

[python]Passing by reference or value| mutable type &immutable type




variable asign in python is  just a reference,
and all data is object.

但是又分為mutable type (list) & immutable type (String)

Function:
  mutable type  :reference
  immutable type:value


範例如下:




print 'List (mutable type)'
def ange_list_reference(the_list):
    print 'got', the_list
    the_list = ['and', 'we', 'can', 'not', 'lie']
    print 'set to', the_list

outer_list = ['we', 'like', 'proper', 'English']

print 'before, outer_list =', outer_list
ange_list_reference(outer_list)
print 'after, outer_list =', outer_list

print '==================================='


print 'String(immutable type)'

def try_to_change_string_reference(the_string):
    print 'got', the_string
    the_string = 'In a kingdom by the sea'
    print 'set to', the_string

outer_string = 'It was many and many a year ago'

print 'before, outer_string =', outer_string
try_to_change_string_reference(outer_string)
print 'after, outer_string =', outer_string


print 'Int (immutable type)'

def change_int(the_int):
    print 'got', the_int
    the_int = '9'
    print 'set to ',the_int

outer_int  = 1

print 'before ,outer_int=',outer_int
change_int(outer_int)
print'after ,outer_int=' ,outer_int



print 'asign operation is use reference not copy'
print 'example:'
L = [1,2,3]
M = ['X' ,L, 'Y']
print M
print 'set L[0]=9'
L[0]=9
print M
print 'the content of M will be set too'


print'============='
print 'if dont want set M, you need use copy'
L = [1,2,3]
M = ['X',L[:],'Y']
print M
print 'set L[0]=9'
L[0] = 9
print M
print 'the content of M wont be set '

consol
===================================
String(immutable type)
before, outer_string = It was many and many a year ago
got It was many and many a year ago
set to In a kingdom by the sea
after, outer_string = It was many and many a year ago
Int (immutable type)
before ,outer_int= 1
got 1
set to  9
after ,outer_int= 1


asign operation is use reference not copy
example:
['X', [1, 2, 3], 'Y']
set L[0]=9
['X', [9, 2, 3], 'Y']
the content of M will be set too
=============
if dont want set M, you need use copy
['X', [1, 2, 3], 'Y']
set L[0]=9
['X', [1, 2, 3], 'Y']
the content of M wont be set

2015年1月31日 星期六

[python] use python-weather-api sample | 如何使用 python-weather-api

API網址python-weather-api
=========================================


wget https://launchpad.net/python-weather-api/trunk/0.3.8/+download/pywapi-0.3.8.tar.gz
tar -zxvf pywapi-0.3.8.tar.gz
cd pywapi-0.3.8/
python setup.py build
python setup.py install
cd .. 


cdoe
import  pywapi
import string
# coding=UTF-8

locate = 'taiwan taipei'

locatMap = pywapi.get_location_ids(locate)

print locatMap.keys()
keylist = []
for key in locatMap.keys():
 keylist.append(key)

usekey =  keylist[0].decode('utf-8')

print "search result: "+ usekey+"\n"

weather_com_result = pywapi.get_weather_from_weather_com(usekey)

yahoo_result = pywapi.get_weather_from_yahoo(usekey)

print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "C now in "+locate + ".\n"

print "Yahoo says: It is " + string.lower(yahoo_result['condition']['text']) + " and " + yahoo_result['condition']['temp'] + locate+".\n"



[python] BMI sample code

use BMI as sample.
this example will use:
math , class, flow control. def function, import src,




bmi.py
import bmiMethod


#read data from file
file = open('people.txt','r')
print 'the content is ',file.name

people = {}

for line in file.readlines():
   print 'read line:',line
   #rstrip = remove '\n'
   part = line.rstrip().split(' ')
   people[part[1]] = part

for key in people.keys():
        peolist = people.get(key)
        name    = peolist[1]
        height  = int(peolist[2])
        weight  = int(peolist[3])
        bmi = bmiMethod.getBmi(height,weight)
        print name,"'s bmi is ",bmi
        peolist.append(repr(bmi))
        people[key] = peolist
        print 'you are',bmiMethod.getRange(bmi)

f = open('people2.txt','w')
for key in people.keys():
 listp = people.get(key)
 str1 = ' '.join(listp)
 f.write(str1+"\n")

f.close()


bmiMethod.py

from __future__ import division

def getBmi(height , weight):
  print 'height = ',height, " weight = " ,weight
  hei2 = float(height/100)*float(height/100)
  bmi =float (weight/hei2)
  print 'bmi = ',bmi
  return bmi

def getRange(bmi):
  if bmi >= 24:
        return 'fat'
  elif bmi < 24 and bmi >= 19:
        return 'normal'
  else :
        return 'thin'


console
the content is  people.txt
read line: 1 lewis 183 70

read line: 2 leo 175 80

read line: 3 jim 170 60

read line: 4 7 170 80

read line: 5 fai 180 70

height =  183  weight =  70
bmi =  20.902385858
lewis 's bmi is  20.902385858
you are normal
height =  180  weight =  70
bmi =  21.6049382716
fai 's bmi is  21.6049382716
you are normal
height =  170  weight =  60
bmi =  20.7612456747
jim 's bmi is  20.7612456747
you are normal
height =  170  weight =  80
bmi =  27.6816608997
7 's bmi is  27.6816608997
you are fat
height =  175  weight =  80
bmi =  26.1224489796
leo 's bmi is  26.1224489796
you are fat
done


people.txt
1 lewis 183 70
2 leo 175 80
3 jim 170 60
4 7 170 80
5 fai 180 70



people2.txt
1 lewis 183 70 20.902385858042937
5 fai 180 70 21.604938271604937
3 jim 170 60 20.761245674740486
4 7 170 80 27.68166089965398
2 leo 175 80 26.122448979591837

2015年1月19日 星期一

[python] 基本語法&用法


variable assign

#one lin comment

"""
multi line comment

"""

#variable assign
x = 1
print x

x += 1

print x

x,y = 1,2
print x,y

x = 1.999
print x

string = "this is stirng"
print string







list:


mlist = [12,45,1]

mlist.append(3)

print mlist

mlist.append(1)

print mlist

print mlist.count(1),mlist.index(1)
print mlist

print mlist.reverse()
mlist.remove(1)

print mlist
print mlist.pop(2)

mlist.append(11);












dictionary
#dictionary

info = {'name': 'lewis'}

print info

info['title']= 'member'
info['age']= '23'
info['locate']= 'taipei'

print info

print info.keys()

print info.get('name')

del info['locate']
print info


#set

channel = set()
channel.add('ylib')
channel.add('zinio')
channel.add('ibobar')

tChannel = {'ibobar','ylib'}

print channel & tChannel
print channel | tChannel
print channel ^ tChannel
print channel - tChannel
print channel - tChannel
print channel | tChannel














String
#String

x = 'i\'m lewis'
print x
y = ',hi1234'
z=x+y
print z

print z[-3]
print z[3:-2]
print z[3:1]

print len(z)

ss='123'

for s in ss:
 print (s , ':')

print z*2

print y in z

#type convertion


i = 10
d = 1.5
f = 3.5
s = "string"
c = 'c'

print int(i+d)
print float(10/2.6)
print i%d
print ord(c)+10
print chr(ord(c)+i)

2015年1月17日 星期六

[python] 快速入門

直接放這張強大的說明圖:




coffeeghost-q-in-py.png


120417-coffeeghost-q-in-py.png




ref: http://tech.marsw.tw/blog/2014/09/03/getting-started-with-python-in-ten-minute

[python]ubuntu下的python相關配置& hellow world

環境:ubuntu14.04.1

此版本已經內建pyhon 2.7.6.
所以本篇大概相關環境設定.

由於android 與java 算是寫了一段時間,所以沒有很仔細地從頭
介紹,所以想說python就記錄的仔細一點好了XD.

1.安裝git (因為方便同步code )

$ sudo apt-get install git
   
2.直接看code最快  (網路上的範例 )

$ git clone https://github.com/cihm/PyConTW2013Tutorial.git

3.安裝編輯器(看個人喜好 )
$ wget http://c758482.r82.cf2.rackcdn.com/Sublime%20Text%202.0.2.tar.bz2
//下載
$ tar -xf "Sublime Text 2.0.2.tar.bz2"
//解壓縮
$ sudo mv "Sublime Text 2" /usr/lib
//移到目錄
$ sudo ln -s "/usr/lib/Sublime Text 2/sublime_text" /usr/bin/st2
//連結到目錄

4.在 Python 標準程式庫中有個 distutils,是用來建立與安裝額外模組,適用於簡易的安裝場合,有些程式庫擴充了 distutils,像是 Setuptools,可以使用以下的指令建立、進入 scripts 資料夾,然後下載、安裝 Setuptools:
$ mkdir scripts
$ cd scripts
$ wget https://bootstrap.pypa.io/ez_setup.py -O - | sudo python
$ sudo easy_install pip
$ sudo pip install virtualenv

ps:安裝套件時,建議可以使用 pip,如果發現有 pip 無法安裝的套件,可以嘗試使用 easy_install,如果這兩個選項都無法安裝,則可以嘗試尋找是否有 setup.py 進行安裝

5.使用 Virtualenv
Python 的套件不少都會直接安裝到 Python 預設的一些系統路徑中,Pip 的 pip-1.4.1-py2.7.egg 就安裝到 /usr/local/lib/python2.7/dist-packages 之中,如果不想都安裝到系統路徑中,或者不具備系統管理者權限而無法安裝到系統路徑,會希望有個虛擬環境可以使用,安裝 Pip 之後,通常會建議安裝 Virtualenv 做為搭配
$ virtualenv --distribute venv
$ cd venv
$ source bin/activate
$ vim hello.py
    hello.py內容為:
    print 'hellow world'


離開 虛擬環境為
deactivate


6.安裝Virtualenvwrapper
是一個 Virtualenv 的 extension,可使虛擬環境的管理變得更容易。
詳細來說,Virtualenvwrapper 提供下述功能:
1.將所有的虛擬環境整合在一個目錄下。
2.管理(新增、移除、複製)所有的虛擬環境。
3.可以使用一個命令切換虛擬環境。
4.Tab 補全虛擬環境的名字。
5.每個操作都提供允許使用者自訂的 hooks。
6.可撰寫容易分享的 extension plugin 系統。

$ easy_install virtualenvwrapper
$ mkdir $HOME/.virtualenvs (之後的虛擬機目錄會放到這)
$ export WORKON_HOME=$HOME/.virtualenvs
$ source /usr/local/bin/virtualenvwrapper.sh (每次用之 前要先執行這行)
$ source ~/.bashrc                    (每次用之 前要先執行這行)

用法:
創建虛擬環境:mkvirtualenv [ENVNAME]
列出所有的虛擬環境:lsvirtualenv
移除虛擬環境:rmvirtualenv ENVNAME
複製虛擬環境:cpvirtualenv ENVNAME TARGETENVNAME
啟動虛擬環境:workon [environment_name]
離開虛擬環境:deactivate
官方文件




ref:http://www.codedata.com.tw/python/python-tutorial-the-1st-class-4-unicode-support-basic-input-output/

ref:http://www.openfoundry.org/tw/tech-column/8516-pythons-virtual-environment-and-multi-version-programming-tools-virtualenv-and-pythonbrew


Virtualenvwrapperref:http://blog.csdn.net/jazywoo123/article/details/37564957