南大慕課《用Python玩轉(zhuǎn)數(shù)據(jù)》-03 數(shù)據(jù)獲取與表示

1. 本地數(shù)據(jù)獲取

1.1 文件處理步驟

  • 打開文件 file_obj = open(filename,mode='r',buffering=-1)
  • 讀文件/寫文件 file_obj.read() / file_obj.write()
  • 關(guān)閉文件 (python)file_obj.close()

1.2 文件的打開.

file_obj = open(filename,mode='r',buffering=-1)

  • filename 是強制參數(shù),后面兩個是可選參數(shù)。
  • mode的默認值為'r'
  • buffering 默認值為-1 (0表示不緩沖,1或大于1的值表示緩沖一行或指定緩沖區(qū)大小),為了加快讀寫速度,盡量使用緩沖
open()函數(shù)-mode

1.3 文件相關(guān)的函數(shù)

  • open()函數(shù)返回的一個文件file對象

  • 文件對象可迭代

  • 文件對象的關(guān)閉和讀寫

    • f.read()、f.write()、f.readline()、f.readlines()、f.writelines()
    • f.close()
    • f.seek()
  • 寫文件-f.write() / 讀文件-f.read()

  • 其他讀寫函數(shù) f.readlines() / f.readline() / f.writelines()

fileobj = open(r'H:\pythonTest1.txt')
cNames = fileobj.readlines()
print cNames
file_obj.close()

['line1\n', 'line2\n', 'line3'] 輸出了文件中的所有行,包含換行符,如果要去除換行符,需要strip函數(shù),python中讀取和寫入都不去除和加入換行符,要自己處理。
python中沒有writeline方法,因為這個與write方法類似,都是寫入單行

  • 其他文件相關(guān)函數(shù)
    file_obj.seek(offset,whence=0)
    在文件中移動文件指針,從whence(0表示文件頭部,1表示當前位置,2表示文件尾部)偏移offset個字節(jié)
    whence參數(shù)可選,默認值為0

1.4 文件讀寫例子

打開一個文件,將每行的字符串加上序號1,2,3,然后寫到另一個文件中。

f1 = open(r"H:\\companies1.txt")
cNames = f1.readlines()   #讀取文件中所有的行
for i in range(0,len(cNames)):
    cNames[i] = str(i+1) + ' ' +cNames[i]  #追加序號到每個字符串中
f1.close
f2 = open(r"H:\\companies3.txt",'w')
f2.writelines(cNames)
f2.close()

2. 網(wǎng)絡(luò)數(shù)據(jù)獲取

2.1 網(wǎng)絡(luò)數(shù)據(jù)如何獲?。孔ト【W(wǎng)頁,解析網(wǎng)頁內(nèi)容

urllib , urllib2 , httplib , httplib2

import urllib
r = urllib.urlopen('http://www.baidu.com/')
html = r.read()
print html

3. 序列

3.1 如下圖都是序列

str = 'Hello, World!' #字符串
aList = [2, 3, 5, 7, 11] #列表
aTuple = ('Sunday', 'happy' ) #元組
pList = [('AXP', 'American Express Company', '86.40'), #元組構(gòu)成的列表
('BA', 'The Boeing Company', '122.64'),
('CAT', 'Caterpillar Inc.', '99.44'),
('CSCO', 'Cisco Systems, Inc.', '23.78')
('CVX', 'Chevron Corporation', '115.91')]

Paste_Image.png
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',\
         'Sunday']
print week[0:3] #['Monday', 'Tuesday', 'Wednesday'], 從索引0開始,3-0 個元素
print week[-7:-4] #['Monday', 'Tuesday', 'Wednesday'],從索引-7 開始,-4-(-7)個元素

3.2 序列相關(guān)操作

  • 標準類型運算符:值比較 / 對象身份比較 / 布爾運算
print 'apple' < 'banana' #True 字符串長度比較
print [1,3,5]  != [2,4,6] #True

aTuple = ('BA', 'The Boeing Company', '122.64') 
bTuple = aTuple  #元組拷貝
print bTuple is not aTuple #False

print   ('86.40' < '122.64') and ('apple' > 'banana')  #False

值比較: < , > , <= , >= , == , != , <>
對象身份比較: is , is not
布爾運算:not , and , or

  • 序列類型運算符:獲取 / 重復(fù) / 連接 / 判斷
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] 
print week[1],'\n', week[-2], '\n', week[1:4], '\n', week[:6], '\n', week[::-1] 
\#Tuesday → week[1]
\#Saturday  → week[-2]
\#['Tuesday', 'Wednesday', 'Thursday']  → week[1:4]
\#['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']  → week[:6]
\#['Sunday', 'Saturday', 'Friday', 'Thursday', 'Wednesday', 'Tuesday', 'Monday'] →week[::-1]  **反轉(zhuǎn)**
print 'apple' * 3    #appleappleapple
print  'pine' + 'apple'    #pineapple
print 'BA' in  ('BA', 'The Boeing Company', '122.64') #True
  • 內(nèi)建函數(shù):序列類型轉(zhuǎn)換工廠函數(shù) / 序列類型可用內(nèi)建函數(shù)

例如 list(), str(), tuple(), unicode(), basestring()

print  list('Hello, World!')  #轉(zhuǎn)換成列表
print  tuple("Hello, World!")  #轉(zhuǎn)換成元組

['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
('H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!')

序列類型有很多內(nèi)建函數(shù),如

enumerate(), len(), max(), min(), sum(), zip(), sorted(), reversed()

aStr = 'Hello,world'
print len(aStr) #11
print sorted(aStr) #[',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']

4. 字符串

4.1 簡介

aStr = 'The Boeing Company'
bStr = "The Boeing Company"
cStr = '''The Boeing
Company'''

單引號,雙引號,三引號都可以用于字符串,其中三引號可以使字符串保持原樣,對于一些需要換行的長字符串非常合適。

aStr = 'The Boeing Company'
bStr = "The Boeing Company"
cStr = '''The Boeing
Company'''

print aStr
print bStr
print cStr

輸入結(jié)果為

The Boeing Company
The Boeing Company
The Boeing
Company

另外,在字符串前加r 也十分方便,能使字符串保持原樣

astr = "C:\Users\legendcos\Desktop\site update\1.code\02.YHS"
print astr

bstr = r"C:\Users\legendcos\Desktop\site update\1.code\02.YHS"
print bstr

結(jié)果為如下,可以看到第一個輸出結(jié)果與期待值不同

C:\Users\legendcos\Desktop\site update?.code?.YHS
C:\Users\legendcos\Desktop\site update\1.code\02.YHS

4.2 字符串的不同表示形式

練習,將"hello,world!" 中的world 替換為python,并計算其中包含的標點符號個數(shù)

aStr = "Hello,World!"
bStr = aStr[:6] + "Python!"
count = 0
for ch in bStr[:]:   #這個意思是取出bStr中的每個字符,因為字符串本身是個序列
    if ch in ',.!?':
        count += 1
cStr = "the count result is %d" %(count)  # 這里是格式運算符

print count  #輸出為 2
print bStr  #輸出為 Hello,Python!
print cStr  #the count result is 2

更多格式運算符


格式運算符輔助符

例如 m.n 控制符

afloat = 23.34567
aStr = "The result is %5.1f" %(afloat)
bStr = "The result is %5.2f" %(afloat)
cStr = "The result is %5.4f" %(afloat)
print aStr
print bStr
print cStr
Paste_Image.png

4.3 字符串的應(yīng)用

+. 判斷回文串, 回文串是一個正讀和反讀都一樣的字符串,比如“l(fā)evel”或者“noon”等等就是回文串。

sStr = "noon"
bStr = ''.join(reversed(sStr))  #前面是兩個單引號
if (sStr == bStr):
    print "yes"
else:
    print "no"

+. 獲取字符串中引號內(nèi)的內(nèi)容

aStr = 'What do you think of this saving "No pain,No gain"?'
#lindex = aStr.index('\"',0,len(aStr)) # 這三行代碼也可以實現(xiàn)功能
#rindex = aStr.rindex('\"',0,len(aStr))
#tempStr = aStr[lindex+1:rindex]
tempStr = aStr.split('\"')[1]  #[1] 表示取被分割后序列的第二個字符串,[0] 則為 What do...saving
if tempStr.istitle():
    print "title"
else:
    print "no title"
print tempStr.title()

輸出結(jié)果為

no title
No Pain,No Gain

字符串中有很多函數(shù),需要時查看幫助 ,比如help(str.index)

轉(zhuǎn)義字符

5. 列表

5.1 列表

  • 可擴展的容器對象
    aList = list('hello.')
    aList →['h', 'e', 'l', 'l', 'o', '.']
    aList[0] = 'H'
    aList →['H', 'e', 'l', 'l', 'o', '.']

  • 包含不同類型的對象
    aList = [1,2,'tex']

5.2 列表的形式

列表的形式
jScores = [9,9,8.5,10,7,8]
aScore = 9
jScores.sort() #排序
jScores.pop() # 去除最高分
jScores.pop(0) # 去除最低分
jScores.append(aScore) # 添加觀眾評分
aveScore = sum(jScores)/len(jScores) # 計算平均分
print aveScore
列表解析

6. 元組

6.1 元組與列表的區(qū)別

列表list [] 方括號表示 ,元組tuple () 園括號表示,list長度 可變,tuple長度不可變

  • 切片
  • 計算長度
    等這些操作都跟list很類似
aTuple = ((1,2,3),4,5)
print aTuple[0][2]  # 輸出 3
bTuple = aTuple[0:2] # 可以切片
print bTuple # 輸出 ((1, 2, 3), 4)
print len(bTuple) # 輸出 2

下面重點說明sorted函數(shù) 和 sort 函數(shù)

aList = ["yahoo","google","su"]
aList[1] = "alibaba"
print aList # 輸出 ['yahoo', 'alibaba', 'su']

#aTuple = ("yahoo","google","su")
#aTuple[1] = "alibaba"
#print aTuple # 這里會出錯,顯示元組不能被重新賦值

bList = [2,3,1,5,3,4]
cList = sorted(bList)
print bList # 輸出 [2, 3, 1, 5, 3, 4] 使用 sorted函數(shù)后,bList內(nèi)容不變,只是生成一個副本 
print cList # 輸出 [1, 2, 3, 3, 4, 5] 生成的副本是排序后的列表
bList.sort()
print bList # 輸出 [1, 2, 3, 3, 4, 5] 函數(shù) sort 會改變原本的內(nèi)容

bTuple = (2,3,1,5,3,4)
cTuple = sorted(bTuple) 
print bTuple # 輸出 (2, 3, 1, 5, 3, 4),不會改變元組內(nèi)容
print cTuple # 輸出 [1, 2, 3, 3, 4, 5] 注意這里生成的是排序后的list列表
#print bTuple.sort() # 因為sort會改變原始的內(nèi)容,而元組的內(nèi)容是不可變的,所以出錯

sorted() 函數(shù) 不會改變原始的內(nèi)容,生成一個排序后的副本列表
sort() 函數(shù)會改變原始內(nèi)容的順序。

6.2 元組的作用

  • 在映射類型中當做鍵來使用
  • 函數(shù)的特殊類型參數(shù)
def func(args1,args2 = "World!"):
    print args1,args2
func("hello,") # 輸出 hello, World!
func("hello,",args2 = "python!") # 輸出 hello, python!
func(args2 = "apple",args1 = "hello,") # 輸出 hello, apple
#....................................................................................#
def func2(args1,*args2):
    print args1
    print args2
func2("hello","yahoo","apple","alibaba")

args2 是一個元組型參數(shù),元組元素長度可變

  • 作為很多內(nèi)建函數(shù)的返回值
返回類型為元組
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容