3 数据获取与表示.pdf

上传人:奉*** 文档编号:4060175 上传时间:2021-01-13 格式:PDF 页数:56 大小:2.96MB
返回 下载 相关 举报
3 数据获取与表示.pdf_第1页
第1页 / 共56页
3 数据获取与表示.pdf_第2页
第2页 / 共56页
点击查看更多>>
资源描述

《3 数据获取与表示.pdf》由会员分享,可在线阅读,更多相关《3 数据获取与表示.pdf(56页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。

1、获取与表示 Where are data from? How to represent data? 数据 本地数据获取 用Python玩转数据 2 用Python获取数据 本地数据如何获取? 文件的打开,读写和关闭 打开后才能进行读写 读文件 写文件 文件为什么需要关闭? 3 文件的打开 4 f1 = open(d:infile.txt) f2 = open(rd:outfile.txt, w) f3 = open(record.dat, wb, 0) Source file_obj = open(filename, mode=r, buffering=-1, ) mode为可选参数,默认值为

2、r buffering也为可选参数,默认值为-1(0代表不缓冲,1 或大于1的值表示缓冲一行或指定缓冲区大小) open()函数-mode ModeFunction r 以读模式打开 w以写模式打开(清空原内容) x以写模式打开,若文件已存在则失败 a以追加模式打开(从EOF开始,必要时创建新文件) r+以读写模式打开 w+以读写模式打开(清空原内容) a+以读和追加模式打开 rb以二进制读模式打开 wb以二进制写模式打开(参见w) ab以二进制追加模式打开(参见a) rb+以二进制读写模式打开(参见r+) wb+以二进制读写模式打开(参见w+) ab+以二进制读写模式打开(参见a+) 5 文

3、件相关函数 返回值 open()函数返回一个文件(file)对象 文件对象可迭代 有关闭和读写文件相关的函数/方法 f.read(), f.write(), f.readline(), f.readlines(), f.writelines() f.close() f.seek() 6 写文件-f.write() file_obj.write(str) 将一个字符串写入文件 firstpro.txt : Hello, World! 7 f = open(firstpro.txt, w) f.write(Hello, World!) f.close() Source with open(firs

4、tpro.txt, w) as f: f.write(Hello, World!) Source 读文件-f.read() file_obj.read(size) 从文件中至多读出size字节数据,返回一个字符串 file_obj.read() 读文件直到文件结束,返回一个字符串 Output: Hello, World! 8 with open(firstpro.txt) as f: p1 = f.read(5) p2 = f.read() print(p1,p2) Source 其他读写函数 file_obj.readlines() file_obj.readline() file_obj

5、.writelines() 9 # Filename: companies_a.py with open(companies.txt) as f: cNames = f.readlines() print(cNames) File Output: GOOGLE Inc.n, Microsoft Corporationn, Apple Inc.n, Facebook, Inc. 文件读写例子 # Filename: revcopy.py with open(companies.txt) as f1: cNames = f1.readlines() for i in range(0, len(cN

6、ames): cNamesi = str(i+1) + + cNamesi with open(scompanies.txt, w) as f2: f2.writelines(cNames) File Output: 1 GOOGLE Inc. 2 Microsoft Corporation 3 Apple Inc. 4 Facebook, Inc. 将文件companies.txt 的字符串前加上序号1、2、3、后写到 另一个文件scompanies.txt中。 10 其他文件相关函数 file_obj.seek(offset , whence=0) 在文件中移动文件指针,从 whence(

7、0表示文件头部,1表示 当前位置,2表示文件尾部)偏 移offset个字节 whence参数可选,默认值为0 11 # Filename: companies_b.py s = Tencent Technology Company Limited with open(companies.txt , a+) as f: f.writelines(n) f.writelines(s) cNames = f.readlines() print(cNames) File 标准文件 当程序启动后,以下三种标准文件有效 stdin标准输入 stdout标准输出 1 2 3 stderr 标准错误 12 n

8、ewcName = input(Enter the name of new company: ) Enter the name of new company: Alibiabia print(newcName) Alibiabia Source import sys sys.stdout.write(hello) 网络数据获取 用Python玩转数据 13 用Python获取数据 网络数据如何获取(爬取)? 抓取网页,解析网页内容 抓取 urllib内建模块 urllib.request Requests第三方库 Scrapy框架 解析 Beautiful Soup库 re模块 14 第三方

9、API抓取 +解析 14 Requests库 15 Requests库是更简单、方便和人性化的Python HTTP第三方库 Requests官网:http:/www.python-requests.org/ 基本方法requests.get() 请求获取指定URL位置的资源,对应 HTTP协议的GET方法 import requests r = requests.get( r.status_code 200 print(r.text) Source 遵循网站爬虫协议 robots.txt # 网站最新更新后抓取时需要增加headers属性,将自己的浏览器信息告诉服务器 headers = U

10、ser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36 r = requests.get( headers = headers) 道指成分股数据 16 利用Requests库获取道指成分股数据 包含多个字符串 AXP, American Express Company, 77.77 BA, The Boeing Company, 177.83 CAT, Caterpillar Inc., 96.39

11、 17 # Filename: dji.py import requests re = requests.get( # the url may change print(re.text) File 网页数据解析 18 BeautifulSoup是一个可以从HTML 或XML文件中提取数据的Python库 官方网站: re/BeautifulSoup/bs4/doc/ re正则表达式模块进行各类正则表 达式处理 参考网站: https:/docs.python.org/3.5/libr ary/re.html 十几十几岁的时候渴慕着小王子,岁的时候渴慕着小王子, 一天之间可以看四十四次日落。是在

12、多久之后才明白,看一天之间可以看四十四次日落。是在多久之后才明白,看 四十四次日落的小王子,他有多么难过。四十四次日落的小王子,他有多么难过。 apple 1,3,5 != 2,4,6 True aTuple = (BA, The Boeing Company, 184.76) bTuple = aTuple bTuple is not aTuple False 86.40 banana False Source 标准类型运算符 = =!= 值比较 is is not 对象身份比较 not and or 布尔运算 25 序列类型运算符 26 week = Monday, Tuesday, We

13、dnesday, Thursday, Friday, Saturday, Sunday print(week1, week-2, n, week1:4, n, week:6, n, week:-1) Tuesday Saturday Tuesday, Wednesday, Thursday Monday, Tuesday, Wednesday, Thursday, Friday, Saturday Sunday, Saturday, Friday, Thursday, Wednesday, Tuesday, Monday apple * 3 appleappleapple pine + app

14、le pineapple BA in (BA, The Boeing Company, 184.76) True Source 序列类型运算符 27 x in s x not in s s + t s * n, n * s si si:j si:j:k 序列类型转换内建函数 28 list() str() tuple() list(Hello, World!) H, e, l, l, o, , , W, o, r, l, d, ! tuple(Hello, World!) (H, e, l, l, o, , , W, o, r, l, d, !) Source 序列类型其他常用内建函数 29

15、enumerate()reversed() len()sorted() max()sum() min()zip() aStr = Hello, World! len(aStr) 13 sorted(aStr) , !, , H, W, d, e, l, l, l, o, o, r Source 字符串 用Python玩转数据 30 字符串的不同表示形式 31 lf = (AXP, American Express Company, 78.51), (BA, The Boeing Company, 184.76), (CAT, Caterpillar Inc., 96.39), (CSCO, C

16、isco Systems, Inc., 33.71), (CVX, Chevron Corporation, 106.09) aStr = The Boeing Company bStr = The Boeing Company cStr = Im a student. dStr = The Boeing company Source 字符串小例子 32 将字符串“Hello, World!”中的“World”替换成“Python”, 并计算其包含的标点符号(由逗号、句号、感叹号和问号组成) 的个数。 Output: 2 # Filename: puncount.py aStr = Hello

17、, World! bStr = aStr:7 + Python! count = 0 for ch in bStr: if ch in ,.!?: count += 1 print(count) File 字符串与输出形式 33 Output: Punctuation marks = 2 Output: There are 2 punctuation marks. format_string % (arguments_to_convert) print(There are %d punctuation marks. % (count) Output: 2 format_string.forma

18、t(arguments_to_convert) print(There are 0:d punctuation marks. .format(count) 类型说明符 34 字符描述 b二进制,以2为基数输出数字 o八进制,以8为基数输出数字 x十六进制,以16为基数输出数字,9以上的数字用小写字母(类型 符为X时用大写字母)表示 c字符,将整数转换成对应的Unicode字符输出 d十进制整数,以10为基数输出数字 f浮点数,以浮点数输出数字 e指数记法,以科学计数法输出数字,用e(类型符是E时用大写E) 表示幂 其他常用格式说明符 35 符号描述 +m.nf输出带符号(若正整数输出“+”号)

19、的数,保留n位小数,整个输出占 m列(若实际宽度超过m则突破m的限制) 5d右对齐,用0填充左边,宽度为5 居中对齐 输出一个 对齐说明符符号说明符最小宽度说明符.精度说明符类型说明符 age, height = 21, 1.758 print(Age:0: cCode = AXP , BA , CAT , CSCO , CVX cPrice = 78.51 , 184.76 , 96.39 , 33.71 , 106.09 for i in range(5): print(: print(I get :d!.format(32) I get 32 ! Source 字符串的应用 37 有一个

20、字符串“acdhdca”,判断其是否是回文串。接着 判断一个数字354435是否是回文数字。 # Filename: compare.py sStr = acdhdca if sStr = .join(reversed(sStr): print(Yes) else: print(No) File sStr = sStr:-1 # Filename: compare.py import operator sStr = acdhdca if operator.eq(sStr, .join(reversed(sStr)=1: print(Yes) else: print(No) File 字符串常用

21、方法 38 capitalize()center()count()encode()endswith()find() format()index()isalnum()isalpha()isdigit()islower() isspace()istitle()isupper()join()ljust()lower() lstrip()maketrans()partition()replace()rfind()rindex() rjust()rpartition()rstrip()split()splitlines()startswith() strip()swapcase()title()tran

22、slate()upper()zfill() 字符串的应用 39 有一些从网络上下载的类似如下形式的一些句子: What do you think of this saying No pain, No gain? 对于句子中双引号中的内容,首先判断其是否满足标题格式,不管满 足与否最终都将其转换为标题格式输出。 tempstr= aStr.split()1 # Filename: totitle.py aStr = What do you think of this saying No pain, No gain? lindex = aStr.index(,0,len(aStr) rindex

23、= aStr.rindex(,0,len(aStr) tempStr = aStrlindex+1:rindex if tempStr.istitle(): print(It is title format.) else: print(It is not title format.) print(tempStr.title() File 转义字符 40 字符说明 0空字符 a响铃 b退格 t横向制表符 n换行 v纵向制表符 f换页 r回车 e转义 双引号 单引号 反斜杠 (在行尾时)续行符 OOO 八进制数OOO代表的字符 xXX十六进制数XX代表的字符 aStr = 101tx41n bSt

24、r = 141tx61n print(aStr, bStr) AA aa Source 列表 用Python玩转数据 41 列表 42 可扩展的 容器对象 包含不同 类型对象 aList = list(Hello.) aList H, e, l, l, o, . aList = list(hello.) aList h, e, l, l, o, . aList0 = H aList H, e, l, l, o, . Source bList = 1, 2, a, 3.5 Source 列表的形式 aList = 1, 2, 3, 4, 5 names = Zhao, Qian, Sun, Li

25、 bList = 3, 2, 1, Action pList = (AXP, American Express Company, 78.51), (BA, The Boeing Company, 184.76), (CAT, Caterpillar Inc., 96.39), (CSCO, Cisco Systems, Inc., 33.71), (CVX, Chevron Corporation, 106.09) 43 列表 44 某学校组织了一场校园歌手比赛, 每个歌手的得分由10名评委和 观众决定,最终得分的规则是去 掉10名评委所打分数的一个最 高分和一个最低分,再加上所有 观众评委分

26、数后的平均值。评委 打出的10个分数为:9、9、8.5、 10、7、8、8、9、8和10,观 众评委打出的综合评分为9,请 计算该歌手的最终得分。 7, 8, 8, 8, 8.5, 9, 9, 9, 10, 10 8, 8, 8, 8.5, 9, 9, 9, 10 8, 8, 8, 8.5, 9, 9, 9, 10, 9 8.72222222222 # Filename: scoring.py jScores = 9, 9, 8.5, 10, 7, 8, 8, 9, 8, 10 aScore = 9 jScores.sort() jScores.pop() jScores.pop(0) jSc

27、ores.append(aScore) aveScore = sum(jScores)/len(jScores) print(aveScore) File 列表 45 将工作日(Monday, Tuesday, Wednesday, Thursday, Friday)和周末(Saturday, Sunday)的表示形式合并,并 将它们用序号标出并分行显示。 Output: 1 Monday 2 Tuesday 3 Wednesday 4 Thursday 5 Friday 6 Saturday 7 Sunday # Filename: week.py week = Monday, Tuesda

28、y, Wednesday, Thursday, Friday weekend = Saturday, Sunday week.extend(weekend) for i,j in enumerate(week): print(i+1, j) File 列表方法 46 append() copy() count() extend() index() insert() pop() remove() reverse() sort() 参数的作用: list.sort(key=None, reverse=False) numList = 3, 11, 5, 8, 16, 1 fruitList = a

29、pple, banana, pear, lemon, avocado numList.sort(reverse = True) numList 16, 11, 8, 5, 3, 1 fruitList.sort(key = len) fruitList pear, apple, lemon, banana, avocado Source 列表解析 47 expression for expr in sequence1 for expr2 in sequence2 . for exprN in sequenceN if condition List comprehensions, list co

30、mps 动态创建列表 简单灵活有用 x for x in range(10) 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 x * 2 for x in range(10) 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 x * 2 for x in range(10) if x * 2 (x+1, y+1) for x in range(2) for y in range(2) (1, 1), (1, 2), (2, 1), (2, 2) Source 生成器生成器表达式表达式 Generator expression sum(x for x in rang

31、e(10) 45 lazy evaluation 元组 用Python玩转数据 48 元组 元组的一般使用与列表类似 49 bTuple = (Monday, 1, 2,3) bTuple (Monday, 1, 2, 3) bTuple01 1 len(bTuple) 3 bTuple1: (2, 3) Source 2014 2014 2014, (2014,) Source 元组 列表元素可以改变 元组元素不可以改变 50 aList = AXP, BA, CAT aTuple = (AXP, BA, CAT) aList1 = Alibiabia print(aList) AXP, A

32、libiabia, CAT aTuple1= Alibiabia print(aTuple) aTuple1=Alibiabia TypeError: tuple object does not support item assignment Source 元组 函数的适用类型 51 aTuple = (3, 5, 2, 4) sorted(aTuple) 2, 3, 4, 5 aTuple (3, 5, 2, 4) aTuple.sort() Traceback (most recent call last): File , line 1, in AttributeError: tuple

33、object has no attribute sort Source aList = 3, 5, 2, 4 aList 3, 5, 2, 4 sorted(aList) 2, 3, 4, 5 aList 3, 5, 2, 4 aList.sort() aList 2, 3, 4, 5 Source 元组的作用 元组用在什么地方? 52 可变长位置参数(元组) Python中函数的参数形式 位置或关键字参数 仅位置的参数 可变长位置参数 可变长关键字参数 (参数可以设定默认值) def foo(args1, args2 = World!): print(args1, args2) foo(He

34、llo,) Hello, World! foo(Hello, args2 = Python!) Hello, Python! foo(args2 = Apple!, args1 = Hello,) Hello, Apple! Source def foo(args1, *argst): print(args1) print(argst) 53 可变长位置参数(元组) def foo(args1, *argst): print(args1) print(argst) foo(Hello, Wangdachui, Niuyun, Linling) Hello, (Wangdachui, Niuyun, Linling) Source 54 元组作为函数特殊返回类型 def foo(): return 1, 2, 3 foo() (1, 2, 3) Source 返回对象的个数返回类型 0None 1object 1tuple 55 小结 56

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 大学资料

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知得利文库网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号-8 |  经营许可证:黑B2-20190332号 |   黑公网安备:91230400333293403D

© 2020-2023 www.deliwenku.com 得利文库. All Rights Reserved 黑龙江转换宝科技有限公司 

黑龙江省互联网违法和不良信息举报
举报电话:0468-3380021 邮箱:hgswwxb@163.com