用python玩转数据第三周_南大慕课《用Python玩转数据》-03 数据获取与表示

1. 本地数据获取

1.1 文件处理步骤

打开文件 file_obj = open(filename,mode='r',buffering=-1)

读文件/写文件 file_obj.read() / file_obj.write()

关闭文件 (python)file_obj.close()

1.2 文件的打开.

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

filename 是强制参数,后面两个是可选参数。

mode的默认值为'r'

buffering 默认值为-1 (0表示不缓冲,1或大于1的值表示缓冲一行或指定缓冲区大小),为了加快读写速度,尽量使用缓冲

open()函数-mode

1.3 文件相关的函数

open()函数返回的一个文件file对象

文件对象可迭代

文件对象的关闭和读写

f.read()、f.write()、f.readline()、f.readlines()、f.writelines()

f.close()

f.seek()

写文件-f.write() / 读文件-f.read()

其他读写函数 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函数,python中读取和写入都不去除和加入换行符,要自己处理。

python中没有writeline方法,因为这个与write方法类似,都是写入单行

其他文件相关函数

file_obj.seek(offset,whence=0)

在文件中移动文件指针,从whence(0表示文件头部,1表示当前位置,2表示文件尾部)偏移offset个字节

whence参数可选,默认值为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. 网络数据获取

2.1 网络数据如何获取?抓取网页,解析网页内容

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'), #元组构成的列表

('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 序列相关操作

标准类型运算符:值比较 / 对象身份比较 / 布尔运算

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

序列类型运算符:获取 / 重复 / 连接 / 判断

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] **反转**

print 'apple' * 3 #appleappleapple

print 'pine' + 'apple' #pineapple

print 'BA' in ('BA', 'The Boeing Company', '122.64') #True

内建函数:序列类型转换工厂函数 / 序列类型可用内建函数

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

print list('Hello, World!') #转换成列表

print tuple("Hello, World!") #转换成元组

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

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

序列类型有很多内建函数,如

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

输入结果为

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

结果为如下,可以看到第一个输出结果与期待值不同

C:\Users\legendcos\Desktop\site update�.code�.YHS

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

4.2 字符串的不同表示形式

练习,将"hello,world!" 中的world 替换为python,并计算其中包含的标点符号个数

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 字符串的应用

+. 判断回文串, 回文串是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串。

sStr = "noon"

bStr = ''.join(reversed(sStr)) #前面是两个单引号

if (sStr == bStr):

print "yes"

else:

print "no"

+. 获取字符串中引号内的内容

aStr = 'What do you think of this saving "No pain,No gain"?'

#lindex = aStr.index('\"',0,len(aStr)) # 这三行代码也可以实现功能

#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()

输出结果为

no title

No Pain,No Gain

字符串中有很多函数,需要时查看帮助 ,比如help(str.index)

转义字符

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 元组与列表的区别

列表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函数 和 sort 函数

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函数后,bList内容不变,只是生成一个副本

print cList # 输出 [1, 2, 3, 3, 4, 5] 生成的副本是排序后的列表

bList.sort()

print bList # 输出 [1, 2, 3, 3, 4, 5] 函数 sort 会改变原本的内容

bTuple = (2,3,1,5,3,4)

cTuple = sorted(bTuple)

print bTuple # 输出 (2, 3, 1, 5, 3, 4),不会改变元组内容

print cTuple # 输出 [1, 2, 3, 3, 4, 5] 注意这里生成的是排序后的list列表

#print bTuple.sort() # 因为sort会改变原始的内容,而元组的内容是不可变的,所以出错

sorted() 函数 不会改变原始的内容,生成一个排序后的副本列表

sort() 函数会改变原始内容的顺序。

6.2 元组的作用

在映射类型中当做键来使用

函数的特殊类型参数

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 是一个元组型参数,元组元素长度可变

作为很多内建函数的返回值

返回类型为元组

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值