首页 / 资讯中心 / 文章详情

人工智能数据处理第三节与第四节

人工智能数据处理第三节与第四节 ★ FEATURED ARTICLE
第三节Python数据结构操作1.列表(List)有序性按照特定的顺序排列可变性可以修改、添加或删除,长度动态变化元素多样性任意数据类型支持切片操作示例包含不同类型的列表mixed_list[1,hello,3.14,True,[1,2,3]]添加元素a[1,2,3,4] a.append(5) print(a) [1,2,3,4,5]切片a[1,2,3,4] print(a[:3]) [1,2,3](1)创建列表创建空列表empty_list[] print(empty_list) []创建整数列表integer_list[1,2,3,4,5] print(integer_list) [1,2,3,4,5](2)访问列表元素fruits[apple,banana,cherry,date] first_fruitsfruits[0] print(first_fruit) apple third_fruitfruits[2] print(third_fruits) cherry(3)修改列表元素fruits[apple,banana,cherry,date] fruits[1]orange print(fruits) [apple,orange,cherry,date]4)增删操作append()insert()remove()pop()del关键字fruits[a,b,c] fruits.append(d) print(fruits) [a,b,c,d] fruits.insert(1,f) print(fruits) [a,f,b,c,d] fruits.remove(b) print(fruits) [a,f,c,d] afruits.pop(1) print(a) f print(fruits) [a,c,d] del fruits[1] print(fruits) [c,d](5)列表切片与遍历a[1,2,3,4,5] for i in a: print(i) 1 2 3 4 5 sliced_aa[1:3] print(sliced_a) [2,3] sliced_a_from_2a[2:] print(sliced_a_from_2) [3,4,5] sliced_a_jiangea[::2] print(sliced_a_jiange) [1,3,5] for i in sliced_a: print(i) 2 3 sliced_a[0]0 print(sliced_a) [0,3] print(a) [1,2,3,4,5]2.元组(Tuple)不可变性元组是静态的一旦创建不可更改(1)创建与访问元组元素student_info(张三,20,90) namestudent_info[0] agestudent_info[1] scorestudent_info[2] print(姓名:name) print(年龄:age) print(成绩:score) 姓名:张三 年龄:20 成绩:903.字典(Dictionary)(1)创建字典my_dict{ name:Alice, age:30, city:New York }(2)访问字典键值对print(my_dict[name]) print(my_dict[age]) Alice 30 print(my_dict.get(address,No address provided)) No address provided(3)修改字典内容my_dict[age]31 my_dict[country]USA print(my_dict[age]) 31 print(my_dict[country]) USA(4)删除字典元素del my_dict[city] valuemy_dict.pop(age) print(value) 30(5)字典的遍历for key in my_dict: print(key) name age city for value in my_dict.values(): print(value) Alice 30 New York for key,value in my_dict.items(): print(key,value) name Alice age 30 city New York文件读写与异常处理1.文件的基本操作(1)打开文件fileopen(example,r) fileopen(example,w) fileopen(example,a)注意文件的编码方式在open()函数可以使用encoding参数来指定编码方式,如encodingutf-8(2)读取文件内容with open(example.txt,r)as file: contentfile.read() print(content) with open(example.txt,r)as file: linefile.readline() print(line) with open(example.txt,r)as file: linesfile.readlines()(3)写入文件内容with open(example.txt,w)as file: file.write(Hello,world!\n) file.write(This is a new line.\n)(4)关闭文件fileopen(example.txt,r) contentfile.read() file.close()方法描述open()打开文件并返回对象read()读取文件全部内容并返回字符串readline()读取文件的一行并返回字符串readlines()读取文件所有行并返回字符串列表write()将字符串写入文件close()关闭文件2.异常处理(1)try-except语句的使用try: ..... except ExceptionType:(2)常见的文件操作异常及处理方法异常类型描述触发条件处理方法FileNotFoundError当尝试打开不存在的文件时触发尝试访问的文件名或路径不正确文件已被删除检查文件名和路径是否正确确认文件是否存在PermissionError当尝试执行没有足够权限的操作时是否触发如读取或写入文件文件或目录的权限设置不允许当前用户执行操作检查文件或目录的权限设置使用具有适当权限的用户执行操作IOError或OSError这是一个通用的输入/输出异常涵盖了多种I/O相关的错误包括文件操作错误。在Python3中IOError已经被OSError取代涉及输入/输出操作的多种错误如设备错误、无效的打开模式等检查代码中的文件操作逻辑确保文件操作正确无误捕获OSError或IOError并根据具体情况处理UnicodeDecodeError当尝试以错误的编码方式读取文件时触发文件内容的编码方式与读取时使用的编码方式不匹配确认文件的正确编码方式在读取文件时指定正确的编码异常类型描述AttributeError当尝试访问对象不存在的属性时触发KeyError在字典操作中当尝试访问不存在的键时触发IndexError在列表、元组或字符串等序列类型中当尝试访问不存在的索引时触发TypeError当操作或函数应用于错误类型的对象时触发。例如尝试将整数和字符串相加NameError当 Python 解释器遇到未定义的变量名时触发SyntaxError当 Python 解释器发现程序中有语法错误时触发ValueError当一个操作或函数接收到一个具有正确类型但值不合适的参数时触发。例如将非数字字符串传递给需要整数的函数ZeroDivisionError当尝试除以零时触发StopIteration当迭代器没有更多的值可供迭代时触发通常在使用 for 循环或 next() 函数时遇到EOFError当输入操作到达文件结束符EOF但没有更多的数据可读时触发try: with open(example.txtr)as file: contentfile.read() except Fil eNotFoundError:#处理文件不存在的异常 print(文件不存在请检查文件名和路径是否正确。 except UnicodeDe codeError:#处理编码错误 print文件编码错误请尝试使用正确的编码方式打开文件。 except PermissionE rror:#处理权限不足 print(文件权限不足” except Exception as e:#处理所有异常 Print(发生了一个处理所有异常异常:e} 发生了一个处理所有异常异常:这是一个自定义错误演示如何触发except Exception3.常用的数据处理库的使用使用np.arayO 的数从 Python 列表或元组创建数组使用np.zeros0函数创建指定大小的零数组使用np.onesO函数创建指定大小的1数组使用np.arange0的数创建指定范围的数组使用np.random.rand0函数创建指定大小的随机数组(1)创建Numpy数组mport numpy as np arr np.array([1,2, 3,4, 5J) print(arr) zeros arr np. zeros(5) print(zeros arr) ones arr np.ones((33 print (ones_arr) random arr np. random. rand(4 4) print(random arr) [1234 5] [0.0.0.0.0.}] [[1.1.1.〕 [1. 1. 1.] [1.1. 1.]] [0.92691172 0471985650.887010750.89931924] [0.93173798 0.911536060.076108490.21844905] [0.937607410.486040020.655788310.31877502] [0.862368870.055238760.606765960.90048091]](2)数组的基本运算arrl np.array([1, 2,3,4,5]) arr2 np.array([5,4,3, 2, 1]) #加法 add result arr1 arr2 print(add result) #减法 sub resultarrl - arr2 print(sub result) #乘法 mul result arrl * arr2 print(mul result) #除法 div result arrl/ arr2 print (div result) [6 6 6 6 6] [-4-2 024J [5898 5] [0.2 0.5 1. 2.5.](3)数组的形状变化arr np.arange(6) print原始数组: arr) reshaped arr arr.reshape(2,3) 原始数组:[0 1 2 3 4 5] 改变形状后的数组: [[O 1 2] [3 4 5]](4)数组的统计与排序函数解析np.mean()计算数组中所有元素的平均值。该函数接收一个数组作为输人并返回该数组中所有元素的平均值。如果数组是多维的并且没有指定axis参数那么它将计算整个数组的平均值。如果指定了axis参数,那么它将沿着指定的轴计算平均值np.sum()计算数组中所有元素的和。与mp.mean0类似它也接收一个数组作为输入并返回该数组中所有元素的和。同样可以通过axis参数来沿着特定轴计算元素的和np.std()计算数组中所有元素的标准差。标准差是衡量数据集中数值分散程度的一个统计量。该函数接收一个数组作为输人并返回该数组中所有元素的标准差。默认情况下 ddof参数为1,意味着在计算标准差时,分母是 N-1(其中N是元素的数量)这是为了进行样本标准差的无偏估计。如果ddof设置为0则分母为N这对应于总体标准差。同样可以通过axis参数来沿着特定轴计算标准差np.sort()对数组中的元素进行排序。该函数接收一个数组作为输人并返回一个新的排序后的数组。默认情况下排序是升序的。可以通过axis参数来沿着特定轴对多维数组进行排序。此外kind参数允许用户选择不同的排序算法如快速排序、归并排序、堆排序等),而order参数则用于指定当数组是结构化数组时,应该按照哪个字段进行排序import numpy as np arr np. array([3, 1,4, 1, 5, 9,2, 6,5,3, 5]) #求平均值 mean value np.mean(arr) print”平均值” mean value) #求和 sum value np.sum(arr) Print(和: sum value) #求标准差 std_ valuenp.std(arr) print标准差: std value) #排序 sorted arr np.sort (arr) Print(排序后的数组:“ sorted_arr) 平均值:4.0 和44 标准差2.256304299271065 排序后的数组:[1 1 2 3 3 4 5 5 6 9](5)Numpy切片操作arry[start:stop:step]arr_ la np.array([0, 1,2,3,4,5,6,7,8,9] slice1d arr_1d[1:5] print(sliceLa_1d) slice ld steparr_ld[::2] print(slice 1d step) [1234] [02468]使用copy方法创建切片的副本slice 2d copyslice_2d.copy() slice 2d copy[O,0]200 print (slice2d_copy) print(arr 2d) [[200 4] [ 6 7]] [[0 1 2] [ 3 4 5] [6 7 8] [9 10 11]](6)省略切片索引slice start omittedarr 2d[1:,:] print (slice start omitted) slice end omitted一 arr 2d[::2] print (slice end omitted) slice step omitted arr_2d[::] print (slice step omitted) [[ 3 4 5] [67 8] [9 10 11]] [[ 0 1] [ 3 4] [6 7] [9 10]] [[0 1 2] [ 3 4 5] [6 7 8] [9 10 11]]2.读取Titanic数据集titanic_dfpd.read_csv(titanic.csv) print(titanic_df.head())(1)数据分析print(titanic_df.info())(2)描述性统计print(titanic_df.describe())(3)唯一值print(titanic_df[Sex].unique())(4)处理缺失值titanic_df_no_natitanic_df.dropna() titanic_df[Age].fillna(titanic_df[Age].median(),inplaceTrue)(5)数据类型转换titanic_df[Sex]titanic_df[Sex].astype(category)(7)数据筛选female_passengerstitanic_df[titanic_df[Sex]female] survived_passengerstitanic_df[titanic_df[Survived]1](8)分组聚合survival_by_sextitanic_df.groupby(Sex)[Survived].sum() print(survival_by_sex)(9)数据可视化import matplotlib.pyplot as plt plt.figure (figsi ze(10,8)) survival_by_sex.plot(kindbar) plt.tit Le(Survival by Sex) plt.xlabel(Sex) plt ylabel(Number of Survived) plt.show()数据采集及存储数据的存储(1)文本文件读取daa{ id:123456, name:张三, age:2 } with open(data.txt,w,encodindutf-8)as file: for key in data.key(): file.write(str(key):str(data[key])\n) with open(data.txt,r,encodingutf-8)as file: linesfile.readline() for line in lines: print(liine.strip())CSV文件读写import csv data [ [张三, 14 岁, 男], [李四, 15 岁, 男], [王一, 16 岁, 女] ] with open(user_data.csv, w, newline, encodingutf-8) as file: writer csv.writer(file) writer.writerow([姓名, 年龄, 性别]) writer.writerows(data) with open(user_data.csv, r, encodingutf-8) as file: reader csv.reader(file) for row in reader: print(row)JSON文件import json data [ {name: 张三, age: 14, sex: 男}, {name: 李四, age: 15, sex: 男}, {name: 王一, age: 14, sex: 女} ] with open(data.json, w, encodingutf-8) as file: json.dump(data, file, ensure_asciiFalse, indent4) with open(data.json, r, encodingutf-8) as file: data json.load(file) for item in data: print(item)数据库的连接和使用开源跨平台高性能安全性可扩展性1基本操作CREATE DATABASE my_database; SHOW DATABASES; USE my_database; DROP DATABASE my_database; CREATE TABLE news ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, link VARCHAR(255) NOT NULL, date DATE NOT NULL ); DESCRIBE news; ALTER TABLE news ADD author VARCHAR(255); DROP TABLE news; INSERT INTO news (title, link, date) VALUES (新闻标题 1, http://example.com/1, 2024-06-08); SELECT * FROM news WHERE date 2024-06-07; UPDATE news SET title 更新后的新闻标题 1 WHERE id 1; DELETE FROM news WHERE id 2;(2)连接MySQL数据库imprort mysql.connector conn mysql.connector.connect( hostlocalhost, userroot, password123456, databasenews ) cursorconn.cursor()3执行SQL操作cursor.execute(CREATE DATABASE IF NOT EXISTS my_database) cursor.execute(USE my_database) cursor.execute( CREATE TABLE IF NOT EXISTS news ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, link VARCHAR(255) NOT NULL, date DATE NOT NULL ) ) #插入数据 insert_query INSERT INTO news (title, link, date) VALUES (%s, %s, %s) data [ (新闻标题 1, http://example.com/1, 2024-06-08), (新闻标题 2, http://example.com/2, 2024-06-07), (新闻标题 3, http://example.com/3, 2024-06-06) ] cursor.executemany(insert_query, data) conn.commit() #查询数据 cursor.execute(SELECT * FROM news) rows cursor.fetchall() for row in rows: print(row) #更新数据 update_query UPDATE news SET title %s WHERE id %s cursor.execute(update_query, (更新后的新闻标题1, 1)) conn.commit() 删除数据 delete_query DELETE FROM news WHERE id %s cursor.execute(delete_query, (2,)) conn.commit() 删除表 cursor.execute(DROP TABLE IF EXISTS news) 关闭游标和连接 cursor.close() conn.close()Python爬虫和数据采集技术(1)分类通用爬虫聚焦爬虫增量爬虫深度爬虫2网络爬虫基本流程URL种子发送请求解析响应提取数据存储数据发现新链接重复上述步骤requests方 法说 明requests.request()构造一个请求支撑以下各方法的基础方法requests.get()获取 HTML 网页的主要方法对应于 HTTP 的 getrequests.head()获取 HTML 网页头信息的方法对应于 HTTP 的 headrequests.post()向 HTML 网页提交 post 请求的方法对应于 HTTP 的 postrequests.put()向 HTML 网页提交 put 请求的方法对应于 HTTP 的 putrequests.patch()向 HTML 网页提交局部修改请求对应于 HTTP 的 patchrequests.delete()向 HTML 页面提交删除请求对应于 HTTP 的 delete属 性说 明r.status_codeHTTP 请求的返回状态200 表示连接成功404 表示失败r.textHTTP 响应内容的字符串形式即 url 对应的页面内容r.renoding从 HTTP header 中猜测的响应内容编码方式r.apparent_encoding从内容中分析出的响应内容编码方式备选编码方式r.contentHTTP 响应内容的二进制形式import requests def getHtml(): url https://www.ynjtc.edu.cn # 网页链接 r requests.get(url) #status_code 为 200 表示请求成功 if r.status_code 200: content r.content.decode(); print(content) else: print(f获取信息失败{r.status_code}) #调用方法执行请求 if __name__ __main__: getHtml()BeautifulSoup解析工具解析器使用方法优点劣势Python 标准库BeautifulSoup(markup, html.parser)Python 的内置标准库、执行速度适中、文档容错能力强Python 2.7.3 及 Python 3.2.2 之前的版本文档容错能力差lxml HTML 解析器BeautifulSoup(markup, lxml)速度快、文档容错能力强需要安装 C 语言库lxml XML 解析器BeautifulSoup(markup, xml)速度快、唯一支持 XML 的解析器需要安装 C 语言库html5libBeautifulSoup(markup, html5lib)最好的容错性、以浏览器的方式解析文档、生成 HTML5 格式的文档速度慢、不依赖外部扩展创建BeautifulSoup对象from bs4 import Beautifulsoup htmlulclass-clearfix lavalamp div class lavalamp-objectidnav/div liid-firstclassnavitem-index Currentahref/index classred首页/a /1i liclasslavalamp-i tema href 国内/a /(Ii liclass lavalamp-itemahref guoji国际/a (1i 1iclass1avalamp-itema href/mil军事/a /1i liclasslavalamp-itema href/finance财经 a/li liclassl avalamp-itema href/ent娱乐/a /1i 1iclass-lavalamp-itema href/internet互联网/a /1i /u]#” #解析并获取 Beautifulsoup 对象 soup-Beauti fulSoup(html1xml)基本元素描述Tag标签最基本的信息组织单元分别用和/标明开头和结尾Name标签的名字p.../p的名字是p,格式:tag.nameAttributes标签的属性字典形式组织格式:tag.attrsNavigableString标签内非属性字符串.../中字符串格式:tag.stringComment标签内字符串的注释部分一种特殊的 Comment 类型选择首页的li标签# 选择 li 标签 print(soup.li) # 输出结果 li classnavitem-index currenta classred href 首页 /a /li # 如果想要获取此标签的内容可以使用 soup.li.string print(soup.li.string) # 输出结果 首页 # 如果想要获取首页 li 标签中的 a 标签属性可以使用 soup.li.a.attrs print(soup.li.a.attrs) # 输出结果 {href: /index, class: [red]} # 如果想要获取如果想要获取首页 li 标签中的 a 标签属性中的 href 属性 # 可以使用 soup.li.a.attrs[href] print(soup.li.a.attrs[href]) # 输出结果 /index属性名值contents获取所有的子节点返回的是一个列表children获取所有的子节点返回的是一个生成器类型descendants获取所有的子孙节点parent获取某个元素的父节点parents获取所有的祖节点返回的是一个生成器类型next_sibling获取节点的下一个兄弟节点previous_sibling获取节点的上一个兄弟节点next_siblings获取节点后所有的兄弟节点返回类型是生产器previous_siblings获取节点前所有的兄弟节点返回类型是生产器常用方法选择函数方 法描 述find_all()返回所有符合条件的元素find()返回第一个匹配的元素find_parents()/find_parent()返回所有祖先节点 / 返回直接的父节点find_next_siblings()/find_next_sibling()返回后面所有的兄弟节点 / 返回后面第一个兄弟节点find_previous_siblings()/find_previous_sibling()返回前面所有的兄弟节点 / 返回前面第一个兄弟节点find_all_next()/find_next()返回节点后所有符合条件节点 / 返回第一个符合条件节点scrapy框架from itemadapter import ItemAdapter import pymysql class MyprojectPipeline: def open_spider(self, spider): # 设置数据库连接 self.connection pymysql.connect( hostlocalhost, port3306, userroot, password123456, dbnews, charsetutf8mb4, cursorclasspymysql.cursors.DictCursor ) self.cursor self.connection.cursor() def close_spider(self, spider): self.connection.close() def process_item(self, item, spider): # 将数据插入到数据库中 self.cursor.execute( INSERT INTO t_news (title, url, date) VALUES (%s, %s, %s), (item[title], item[url], item[date]) ) self.connection.commit() return item
阅读完成 · 觉得有帮助?
咨询建站