In [2]:
print "Hello World"


Hello World

In [5]:
a = 3 
a + 2


Out[5]:
5

In [6]:
print "Hello World"


Hello World

In [12]:
import requests
from bs4 import BeautifulSoup as bs
import jieba
res = requests.get('https://www.ptt.cc/bbs/Soft_Job/index.html', verify=False)
soup = bs(res.text)
dic = {}
for ent in  soup.select('.r-ent'):
    for w in jieba.cut(ent.select('.title')[0].text.strip()):
        if w not in dic:
            dic[w] = 1
        else:
            dic[w] = dic[w] + 1
            
#for ele in  dic:
#    print ele, dic[ele]


C:\Python27\lib\site-packages\requests\packages\urllib3\util\ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
C:\Python27\lib\site-packages\requests\packages\urllib3\connectionpool.py:768: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html
  InsecureRequestWarning)

In [13]:
# this is a comment

'''
multiple
comments
'''


Out[13]:
'\nmultiple\ncomments\n'

In [16]:
# int a = 3;
a = 3
print type(a)
b = "hello world"
print type(b)
a + b


<type 'int'>
<type 'str'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-c522e7ae42df> in <module>()
      4 b = "hello world"
      5 print type(b)
----> 6 a + b

TypeError: unsupported operand type(s) for +: 'int' and 'str'

In [19]:
import sys

# This is a single line comment
def main():
    print 'Hello World'

In [20]:
main()


Hello World

In [24]:
import sys
#help(sys)
#?sys
#dir(sys)
help(sys.exit)


Help on built-in function exit in module sys:

exit(...)
    exit([status])
    
    Exit the interpreter by raising SystemExit(status).
    If the status is omitted or None, it defaults to zero (i.e., success).
    If the status is an integer, it will be used as the system exit status.
    If it is another kind of object, it will be printed and the system
    exit status will be one (i.e., failure).


In [25]:
print ("Hello from python")


Hello from python

In [24]:
input("How are you?")


How are you?"Hi"
Out[24]:
'Hi'

In [30]:
answer = input("How are you?")


How are you?"123"

In [5]:
answer = raw_input("How are you?")


How are you?hi

In [6]:
print answer


hi

In [10]:
name = raw_input("What is your name? ")
if name == "David":
    print "Nice to mee you! " + name
elif name == "John":
    print "Hi John"
else:
    print ("Your name again?")


What is your name? John
Hi John

In [17]:
name = raw_input("What is your name? ")
age = raw_input("How old are you? ")

# Method 1: concat phrases with +
#print "My name is "+ name + ", and I am " + age + " years old"

# Method 2: {} best
#print "My name is {}, and I am {} years old".format(name, age)

# Method 3: {} with index best
#print "My name is {0}, and I am {1} years old".format(name, age)
#print "My name is {1}, and I am {1} years old".format(name, age)

# Method 4: %s => str, %d => int
#print "My name is %s, and I am %d years old"%(name, int(age))


What is your name? David
How old are you? 31
My name is David, and I am 31 years old

In [20]:
print "http://www.appledaily.com.tw/realtimenews/article/finance/20150908/687086/%E5%93%80%E9%B3%B3%E5%8F%B2%E4%B8%8A%E6%9C%80%E8%96%84%E3%80%80%E6%98%8E%E5%B9%B4i7%E5%83%856mm/{}".format('1')
print "http://www.appledaily.com.tw/realtimenews/article/finance/20150908/687086/%E5%93%80%E9%B3%B3%E5%8F%B2%E4%B8%8A%E6%9C%80%E8%96%84%E3%80%80%E6%98%8E%E5%B9%B4i7%E5%83%856mm/%s"%('1')


http://www.appledaily.com.tw/realtimenews/article/finance/20150908/687086/%E5%93%80%E9%B3%B3%E5%8F%B2%E4%B8%8A%E6%9C%80%E8%96%84%E3%80%80%E6%98%8E%E5%B9%B4i7%E5%83%856mm/1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-bcf1b91c12d0> in <module>()
      1 print "http://www.appledaily.com.tw/realtimenews/article/finance/20150908/687086/%E5%93%80%E9%B3%B3%E5%8F%B2%E4%B8%8A%E6%9C%80%E8%96%84%E3%80%80%E6%98%8E%E5%B9%B4i7%E5%83%856mm/{}".format('1')
----> 2 print "http://www.appledaily.com.tw/realtimenews/article/finance/20150908/687086/%E5%93%80%E9%B3%B3%E5%8F%B2%E4%B8%8A%E6%9C%80%E8%96%84%E3%80%80%E6%98%8E%E5%B9%B4i7%E5%83%856mm/%s"%('1')

TypeError: float argument required, not str

In [32]:
a = 3
b = 2
print a + b 
print a - b

c = 1.5
d = 2.5
print c + d
print c - d

print type(a + b)
print type(c + d)


5
1
4.0
-1.0
<type 'int'>
<type 'float'>

In [35]:
s = '2'
print type(s)
int(s)
print type(int(s))

print s + '34567'
print int(s) + 34567


<type 'str'>
<type 'int'>
234567
34569

In [42]:
print float(2)
print float(3.2)

print 2/3
print float(2/3)

# print numeric after period
print float(2)/3
print 2.0/3
print 2 /3.0


2.0
3.2
0
0.0
0.666666666667
0.666666666667
0.666666666667

In [45]:
print 'qoo'
print 'qoo' * 3
print '?' * 8


qoo
qooqooqoo
????????

In [46]:
times = raw_input("Repeat Times: ")
print("Qoo " * int(times))


Repeat Times: 5
Qoo Qoo Qoo Qoo Qoo 

In [49]:
print 1/3
print 1.0 /3

# print with comma
print 1/3,
print 1/3.0


0
0.333333333333
0 0.333333333333

In [52]:
print 1/3
print 3/3


0
1

In [53]:
3/0


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-53-a0641230c7a8> in <module>()
----> 1 3/0

ZeroDivisionError: integer division or modulo by zero

In [54]:
try:
    3/0
except ZeroDivisionError:
    print "three divides to 0 shows zero devision error"


three divides to 0 shows zero devision error

In [60]:
dividend = raw_input("Dividend: ")
divisor = raw_input("Divisor: ")

try:
    print float(dividend) / float(divisor)
except ZeroDivisionError as detail:
    print "ZeroDvisionError", detail


Dividend: 3/0
Divisor: 0
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-60-324fba9d1f83> in <module>()
      3 
      4 try:
----> 5     print float(dividend) / float(divisor)
      6 except ZeroDivisionError as detail:
      7     print "ZeroDvisionError", detail

ValueError: invalid literal for float(): 3/0

In [61]:
dividend = raw_input("Dividend: ")
divisor = raw_input("Divisor: ")

try:
    print float(dividend) / float(divisor)
except ValueError as detail:
    print "ValueError", detail
except ZeroDivisionError as detail:
    print "ZeroDvisionError", detail


Dividend: 3/0
Divisor: 0
ValueError invalid literal for float(): 3/0

In [63]:
dividend = raw_input("Dividend: ")
divisor = raw_input("Divisor: ")

try:
    print float(dividend) / float(divisor)
except: 
    print "error"


Dividend: 3/0
Divisor: 0
error

In [66]:
print "hello world"
print 'hello world'
print "this is a 'book' "
print 'this is a "book"'


hello world
hello world
this is a 'book' 
this is a "book"

In [68]:
a = 'hi this is a l\
ong text'
print a

a = '''hi this is a l
ong text'''
print a


hi this is a long text
hi this is a l
ong text

In [78]:
s = 'hello world'
print s[0]
print s[1]
print s[-1]
print s[-2]


h
e
d
l

In [81]:
print len(s)
print s + ' yoyo'


11
hello world yoyo

In [77]:
import os
for f in  os.listdir('../'):
    if f[0] == '.':
        print f


.android
.appcfg_nag
.cache
.config
.continuum
.deltafy
.eclipse
.gem
.gitconfig
.gitignore
.heroku
.ipynb_checkpoints
.ipython
.m2
.matplotlib
.RData
.Rhistory
.rnd
.ssh
.titanium
.vagrant.d
.VirtualBox

In [84]:
s = '30'
print s + 'yoyo'
print int(s) + 50


age = 30
print "my age is " + str(age)


30yoyo
80
my age is 30

In [85]:
# \t => tab, \n => new line

raw = '\n\t this is a \t line with format \t\n'
print raw


	 this is a 	 line with format 	


In [86]:
raw = r'\n\t this is a \t line with format \t\n'
print raw


\n\t this is a \t line with format \t\n

In [87]:
raw = repr('\n\t this is a \t line with format \t\n')
print raw


'\n\t this is a \t line with format \t\n'

In [92]:
a = 'Qoo loves OOP'
print a.split()
print a.upper()
print a.lower()
print dir(a)
print a.title()


['Qoo', 'loves', 'OOP']
QOO LOVES OOP
qoo loves oop
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Qoo Loves Oop

In [93]:
a = 'Qoo loves OOP'
print a.isdigit()


False

In [98]:
import os
for f in os.listdir('../'):
    if f.split('.')[-1] == 'txt':
        print f


2005.patch.txt
2006.patch.txt
2008.patch.txt
2009.patch.txt
51081295_102-0400-1-051.txt
a1.txt
aliblast.txt
apple.txt
bid_detail.txt
bid_list.txt
blastres.txt
comedies.txt
complete-testoutput1.txt
complete-testoutput2.txt
complete-testoutput3.txt
corr-testoutput1.txt
corr-testoutput2.txt
corr-testoutput3.txt
err.txt
f1.txt
f2.txt
getmonitor-testoutput1.txt
getmonitor-testoutput2.txt
ingredients_copy.txt
LICENSE.txt
links.txt
match.txt
match1.txt
myfile.txt
new  3.txt
stock1.txt
t1.txt
t2.txt
t3.txt
test.txt
y1_text.txt

In [107]:
import requests
from bs4 import BeautifulSoup as bs 

headers  = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.262 Safari/537.36'}
res = requests.get('http://ck101.com/', headers = headers)
soup = bs(res.text)
for img in soup.select('img'):
    if 'png' in img.get('src') or 'jpg' in img.get('src') or 'gif' in img.get('src'):
        print img.get('src').split('/')[-1]


atrk.gif?account=1Nevh1aYY900M9
gwqavAO.png
gift.png
loading.gif
loginSafety.png
vUiZzlO.jpg
6Ocuyjp.jpg
63b1538127fa4d51bff31b698209ed10.jpg
bmdQ9MR.jpg
pVFHHqR.jpg
e5ujgGi.jpg
db9d82f02c3d4c9362a04bc34889a1cc.jpg
1n8Rxn5.png
812ba36d0c9d113a3b71c5c2d1fc5f18.jpg
0c68244b4261c3c95ebd2ca460c4916e.jpg
f6VFvxm.jpg
79RxEeu.jpg
5742ac0970c5a103dd2aed730bc70534.jpg
ZHqlDsl.jpg
766b3822283a4edefdadd2f9244bd127.jpg
e5f47cfbe15af25ce2959359a0a7e293.jpg
8c6dd80c74b0006ec195bd230e0e3140.jpg
a1fa27638f13a9d7e8774f4ff7202b00.jpg
68c7b011ab8bdc6251269a488b084ca5.jpg
a746e3a5d8d64fe79406951bd01ae121.jpg
f1c0ae244650d0fdf3de73d2ab44fb6a.jpg
7efa29d7fdf112f8c50527b06c2be1a8.jpg
842963581997c866bb221ed3e4652811.jpg
e7b5e68103675fd3a92cc787b40044fe.jpg
7744dff231c7dc09f173e44230bedaed.jpg
10ee4a345d3332feb3c4d1bf34a192e5.jpg
c13cad0fe4d096cbb0b7607fd5ebb647.jpg
60ba7b5d1ac6ebf0cc2fd542dca6607f.jpg
93ad854cf660978fc810f44941d631a1.jpg
ccc724e989fba0016a79bf061c737da5.jpg
c40a54e2f679cbc6bfe737e4cdc4a6e5.jpg
156f14a3e27352711ca6a51275c7f22c.jpg
12d36d90bf79eaf5c9797baa75d7863e.jpg
fe54877aa46604c9a4834c3eeaafa1fe.jpg
b39c6c68844123a483f80bc8f6cc9a39.jpg
57a1a02821ef82b4bdb018c3ee5a6f4d.jpg
0ac6f5e6ff26658eac3e8af027561efc.jpg
5b6fea024c70275867b1084beef2bc80.jpg
01d01f768891e9a37551d02fed0ad5d7.jpg
fd00f7d2f96e35c8044418415092d373.jpg
fd0d213a10b53a212cce7eeebf934040.jpg
19ba560c5210ddc1593d5cd6808fd9be.jpg
bbaa470241394d8abc542ce7908f115e.jpg
809ee868838fd51a7737bfb6d786810f.jpg
412d7b42e99cddcf73dfc76706440459.jpg
0c5668c819b9b6c4c817d66a29843ee5.jpg
a2e52bb9fc1876e719aa421b552d553e.jpg
0e38b0527d1d99d4df6926a2fa39c527.jpg
1110af6f3c99e82de16cbcb0b864bfbd.jpg
50cfdd317ec2ddea2f223512e095ea8d.jpg
a58077421548bd2296f4d5e5d3678171.jpg
3dd2d1c63c1f348094964690d1c63315.jpg
22e070fed73926f51c5bd6755c7d1583.jpg
db8387310a0337e4e379888b716d0a69.jpg
25adcfbde85aa87fe2b99a5ce823e966.jpg
d2d4ee0f295179c421cdd4b3318efea5.jpg
a29fea0025255483cf7e217208e0980f.jpg
dd0a6d05dddf84fb9e31516d8d0e5805.jpg
132036ddj2p5d7md0bvpm2.jpg
135528kumxyfqdbx9qwqzh.jpg
141512qgvv2md56zmmxhjk.jpg
142029dn77v4f3753pf775.jpg
currykid.jpg
120600y1cy46ocyqc4qbyq.png
120714hq0urr42jn8qzee8.jpg
120923c1l474kl1469q68z.png
5deecb22554c4b8afee15b4bd54e7667.jpg
4f7addfcf822c32ee173eb6e9274c7fc.jpg
1b6cc43f61c70ab63d212db1f818f3d6.jpg
f9570839689edd13e978f29ba6e27846.jpg
34a221278eac38ca08d390adc2d288f6.jpg
f2d26bc3fe427bfbcfaabc9d28e3e4da.jpg
db9d2bc87986589b983437ed00c075f7.jpg
2ffce0cb10ef596538fe604fef2b0683.jpg
sDEJfhd.gif
IPl4NjW.gif
qLTpZKN.jpg
Chatjo1.png
o1u5cDrq.jpg
wDKJ5N2q.jpg
CjUTDfyq.jpg
131523araljjj40ljgzrjp.jpg.thumb.jpg
1111142301c61cc54cd7a1042a.jpg
1104032050ee1abecf7d7e9da0.jpg
1613145.jpg
0068d8657e9124edb738550072f92762.jpg
78018e2db2700171e0689c04ab3bd5ff.jpg
fbf5423265d1c9104e037acdd488e39f.jpg
f1f7a0903301c0aaa7c08a09de6a2d9a.jpg
2141825be1f60d8f85e826809ac999ad.jpg
f945e11c934c9b98ea79630663d8ae3c.jpg
fdf695b6b73d2ee2ae96707e8e5cc67f.jpg
J5Gb1cg.png
uRAEOyG.png
rnP561E.png
BDVgDK5.png
N6D4k1b.png
UYRcFli.png
VASHc2D.png
Li6qldX.png
BFYowLq.jpg
G6C66zm.jpg
3KCC9CX.jpg
4ZqpSJq.jpg
wresPWp.jpg
ECD286k.jpg
CclhWgE.jpg
Gr6cmvQ.jpg
wHQg0E5.png
NBvsr7X.png
ad_close.gif
lIcQk78.jpg

In [115]:
import requests
import shutil
from bs4 import BeautifulSoup as bs 

headers  = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.262 Safari/537.36'}
res = requests.get('http://ck101.com/', headers = headers)
soup = bs(res.text)

for img in soup.select('img'):
    fname = img.get('src').split('/')[-1]
    extension = fname.split('.')[1]
    if  extension in ['png', 'gif', 'jpg']:
        #print fname
        response = requests.get(img.get('src'), headers = headers, stream=True)
        with open(fname, 'wb') as out_file:
            shutil.copyfileobj(response.raw, out_file)
        del response


---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-115-7c04add071ec> in <module>()
     14         response = requests.get(img.get('src'), headers = headers, stream=True)
     15         with open(fname, 'wb') as out_file:
---> 16             shutil.copyfileobj(response.raw, out_file)
     17         del response
     18 

C:\Python27\Lib\shutil.pyc in copyfileobj(fsrc, fdst, length)
     47     """copy data from file-like object fsrc to file-like object fdst"""
     48     while 1:
---> 49         buf = fsrc.read(length)
     50         if not buf:
     51             break

C:\Python27\lib\site-packages\requests\packages\urllib3\response.pyc in read(self, amt, decode_content, cache_content)
    241                 else:
    242                     cache_content = False
--> 243                     data = self._fp.read(amt)
    244                     if amt != 0 and not data:  # Platform-specific: Buggy versions of Python.
    245                         # Close the connection when no data is returned

C:\Python27\Lib\httplib.pyc in read(self, amt)
    565         # connection, and the user is reading more bytes than will be provided
    566         # (for example, reading in 1k chunks)
--> 567         s = self.fp.read(amt)
    568         if not s and amt:
    569             # Ideally, we would raise IncompleteRead if the content-length

C:\Python27\Lib\socket.pyc in read(self, size)
    378                 # fragmentation issues on many platforms.
    379                 try:
--> 380                     data = self._sock.recv(left)
    381                 except error, e:
    382                     if e.args[0] == EINTR:

error: [Errno 10054] 遠端主機已強制關閉一個現存的連線。

In [117]:
import string
a = 'Qoo loves OOP'
print a.split()
string.join(a.split(), '-') # 'Qoo-loves-OOP'

a = 'Qoo loves OOP'
'-'.join(a.split())


['Qoo', 'loves', 'OOP']
Out[117]:
'Qoo-loves-OOP'

In [121]:
a = 'Qoo loves OOP'
print a.split()
print '@'.join(a.split())

a = 'adsf                     df                                    sdf                 sdf'
print a.split()
print ' '.join(a.split())


['Qoo', 'loves', 'OOP']
Qoo@loves@OOP
['adsf', 'df', 'sdf', 'sdf']
adsf df sdf sdf

In [122]:
s = 'hello'
s[1:4]   , \
s[1:]    , \
s[:]     , \
s[1:100] , \


Out[122]:
('ell', 'ello', 'hello', 'ello')

In [123]:
s = 'hello'
s[-1] , \
s[-4] , \
s[:-3] , \
s[-3:] , \


Out[123]:
('o', 'e', 'he', 'llo')

In [125]:
s = 'hello'
# for(i = len(s); i> 0 ; i--)
print s[::-1]


a = 'abcdedcba'
print a==a[::-1]


olleh
True

In [128]:
#String Formatting 
print 'The results are {} and {}'.format(3.14159, 5)

# str => %s int => %d float => %f
print 'The results are %.02f and %d' % (3.14159, 5)


The results are 3.14159 and 5
The results are 3.14 and 5

In [132]:
a = '123'
#print dir(a)
print a.__str__


<method-wrapper '__str__' of str object at 0x033D4ED8>

In [133]:
import os
for f in os.listdir('./'):
    print f


.git
.ipynb_checkpoints
20150908 Python Basic.ipynb
gwqavAO.png
loading.gif
README.md
test.py

In [137]:
ary =  ['hello', 'world' , 3]
print ary[0] + ' yoyo'
print ary[2] + 5


hello yoyo
8

In [138]:
print list("word")


['w', 'o', 'r', 'd']

In [144]:
ary =  [['list'], ['of', 'lists']]
print ary[0]
print ary[1]
print ary[1][0]

print list(('a', 1))
a = ['heterogeneous', 3]
a[1] + 5


['list']
['of', 'lists']
of
['a', 1]
Out[144]:
8

In [146]:
a = [5, 6, 7, 's'] # a = [5 6 7 ‘s’] 
print a[0] # 5
print a[2:4] # [7, ‘s’] 
print a[-1] # ‘s’ 
print a[-2] # 7
print a[2:] # [7, ‘s’]
print a[::2] # [5, 7]
print a[::-1] # [‘s’, 7, 6, 5]
print len(a) # 4
print [min(a), max(a)] # [5, ‘s’]


5
[7, 's']
s
7
[7, 's']
[5, 7]
['s', 7, 6, 5]
4
[5, 's']

In [150]:
a = [5, 6, 7, 8]
print a
a.pop()
print a
a.append(2) # a = [5, 6, 7, 2]
print a
a.sort() # a = [2, 5, 6, 7]
print a


[5, 6, 7, 8]
[5, 6, 7]
[5, 6, 7, 2]
[2, 5, 6, 7]

In [151]:
print a[::-1]
print a

a.reverse() # a = [7, 6, 5, 2]
print a


[7, 6, 5, 2]
[2, 5, 6, 7]
[7, 6, 5, 2]

In [154]:
a.remove(6)

In [155]:
print a


[7, 5, 2]

In [156]:
print dir(a)


['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

In [157]:
a= [1,23,2,4,1,2,3,1,4,5]
print a.count(1)


3

In [158]:
print help(a.insert)


Help on built-in function insert:

insert(...)
    L.insert(index, object) -- insert object before index

None

In [160]:
print a
a.insert(3,'qoo')
print a


[1, 23, 2, 4, 1, 2, 3, 1, 4, 5]
[1, 23, 2, 'qoo', 4, 1, 2, 3, 1, 4, 5]

In [164]:
for qoo in os.listdir('../'):
    if 'txt' in qoo:
        print qoo


2005.patch.txt
2006.patch.txt
2008.patch.txt
2009.patch.txt
51081295_102-0400-1-051.txt
a1.txt
aliblast.txt
apple.txt
bid_detail.txt
bid_list.txt
blastres.txt
comedies.txt
complete-testoutput1.txt
complete-testoutput2.txt
complete-testoutput3.txt
corr-testoutput1.txt
corr-testoutput2.txt
corr-testoutput3.txt
err.txt
f1.txt
f2.txt
getmonitor-testoutput1.txt
getmonitor-testoutput2.txt
ingredients_copy.txt
LICENSE.txt
links.txt
match.txt
match1.txt
myfile.txt
new  3.txt
stock1.txt
t1.txt
t2.txt
t3.txt
test.txt
y1_text.txt

In [168]:
import requests
from bs4 import BeautifulSoup as bs
res = requests.get('https://www.ptt.cc/bbs/Soft_Job/index.html', verify=False)
soup = bs(res.text)
for title in soup.select('.r-ent'):
    if '新鮮人'.decode('utf-8') in title.select('.title')[0].text:
        print title.select('.title')[0].text.strip()


C:\Python27\lib\site-packages\requests\packages\urllib3\util\ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
C:\Python27\lib\site-packages\requests\packages\urllib3\connectionpool.py:768: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html
  InsecureRequestWarning)
[請益] 新鮮人進公司多快上工?
Re: [請益] 新鮮人進公司多快上工?

In [170]:
list('a')
hello =  list('hello world')
print hello
print 'e' in hello
print 'a' in hello


['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
True
False

In [171]:
a = [1, 2, 3]
print "a:", a
b = a
print "a:", a
print "b:", b

a[1] = 2000
print "a:", a
print "b:", b


a: [1, 2, 3]
a: [1, 2, 3]
b: [1, 2, 3]
a: [1, 2000, 3]
b: [1, 2000, 3]

In [172]:
a = [1, 2, 3]
import copy
b = copy.deepcopy(a) # Deep Copy
a[1] = 2000
print "a:", a
print "b:", b


a: [1, 2000, 3]
b: [1, 2, 3]

In [173]:
nums = [1, 2, 3, 4]
square = []
for n in nums:
    square.append(n * n)
print square


[1, 4, 9, 16]

In [174]:
nums = [1, 2, 3, 4]
squares = [ n * n for n in nums ]   
print squares


[1, 4, 9, 16]

In [175]:
nums = [2, 8, 1, 6]
small = []
for n in nums:
    if n <= 2:
        small.append(n)
print small


[2, 1]

In [176]:
small = [ n for n in nums if n <= 2 ]  ## [2, 1]
print small


[2, 1]

In [178]:
fruits = ['apple', 'cherry', 'bannana', 'lemon']
afruits = []
for s in fruits:
    if 'a' in s:
        afruits.append(s.upper())
print afruits


['APPLE', 'BANNANA']

In [179]:
afruits = [ s.upper() for s in fruits if 'a' in s ]
print afruits


['APPLE', 'BANNANA']

In [ ]:


In [ ]:


In [7]:
contact_list = []

while True:
    contact = raw_input("Add Contact: ")
    if contact == "Done":
        break
    else:
        contact_list.append(contact)
        print "now, you have {} contacts".format(len(contact_list))

print "Your contacts are: " + ', '.join(contact_list)


Add Contact: Mary
now, you have 1 contacts
Add Contact: John
now, you have 2 contacts
Add Contact: David
now, you have 3 contacts
Add Contact: Done
Your contacts are: Mary, John, David

In [9]:
# for(int i = 1; i< 10 ; i ++)
print range(1,10)
for i in range(1,10):
    print i + 5


[1, 2, 3, 4, 5, 6, 7, 8, 9]
6
7
8
9
10
11
12
13
14

In [11]:
#if - else
a = 9
b = 8
for i in range(1,200):
    if i == a:
        print(str(a) + ' found!')
        break
    elif i == b:
        print str(b) + ' found'
    else:
        print(str(a) + ' was not in the list')


9 was not in the list
9 was not in the list
9 was not in the list
9 was not in the list
9 was not in the list
9 was not in the list
9 was not in the list
8 found
9 found!

In [12]:
# from 1 to 10
for i in range(1,10):
    print i,
    
print


1 2 3 4 5 6 7 8 9

In [22]:
# step by 2
for i in range(1,10,2):
    print i,

print

print range(1,10,2)
print range(1,10,3)
print range(10,1,-1) # for(i = 10; i> 1; i--)

print range(-1, -5, -1)


1 3 5 7 9
[1, 3, 5, 7, 9]
[1, 4, 7]
[10, 9, 8, 7, 6, 5, 4, 3, 2]
[-1, -2, -3, -4]

In [14]:
# Iterate over list
a = [1,2,3,4,5]
for i in a:
    print i,


1 2 3 4 5

In [15]:
# Iterate over list
a = [1,2,3,4,5]
for qoo in a:
    print qoo,


1 2 3 4 5

In [32]:
i =0
suma = 0 
while(i < 101):
    suma += i
    i +=1
print suma


5050

In [1]:
sum(range(1,101))


Out[1]:
5050

In [2]:
# dry =>  do not repeat yourself
def say_hello():
    print "hello world"

In [3]:
say_hello()


hello world

In [4]:
def addNum(a, b):#Define Function
    return a+b #Return function 

print addNum(1,4)


5

In [5]:
import math
a = math.ceil(3.6)
print a


4.0

In [7]:
import math #Importing Modules
print math #Print Content


<module 'math' (built-in)>

In [8]:
import sys #Importing Modules
print(sys.argv) #Print Argument


['C:\\Python27\\lib\\site-packages\\IPython\\kernel\\__main__.py', '-f', 'C:\\Users\\david\\.ipython\\profile_default\\security\\kernel-9a7bb05e-02d2-4a15-86b1-76a94314a86f.json', '--profile-dir', 'C:\\Users\\david\\.ipython\\profile_default']

In [9]:
print len(sys.argv)


5

In [10]:
def add_contact(name):
    contact_list.append(name)
    print "You have %d contacts" % (len(contact_list))

def get_contact():	
    return "Your Contacts: %s"%(contact_list)

In [12]:
contact_list = []

def main():    
    while True:
        contact = raw_input("Add Contact: ")
        if contact == 'Done':
            break
        else:
            add_contact(contact)
    print get_contact()

main()


Add Contact: John
You have 1 contacts
Add Contact: May
You have 2 contacts
Add Contact: David
You have 3 contacts
Add Contact: Done
Your Contacts: ['John', 'May', 'David']
None

In [ ]: