文章目录
- 电影数据爬取阶段
- 数据爬取阶段项目代码
- 1. ModuleNotFoundError: No module named 'xlwt'
- 2. AttributeError: module 'urllib' has no attribute 'request'
- 3. UnboundLocalError: local variable 'xxx' referenced before assignment
- 4. SyntaxError: invalid syntax
- 5. NameError: name 'saveData' is not defined
- 6. IndexError: list index out of range
- 7. ModuleNotFoundError: No module named 'MySQLdb'
- 8. UnicodeEncodeError: 'charmap' codec can't encode characters in position 285-290: character maps to
- 9. (2019, "Can't initialize character set utf-8 (path: compiled_in)")
- 10. 'gbk' codec can't encode character '\xa0' in position 339: illegal multibyte sequence
- 11. (1136, "Column count doesn't match value count at row 1")
- 12. TypeError: object of type 'NoneType' has no len()
- 13. TypeError: can't concat str to bytes
- 信息图像化阶段
- 基于mysql的本阶段代码
- 基于excel的本阶段代码
- 1. cursor.execute(sql)的返回值问题
- 2. ModuleNotFoundError: No module named 'jieba'
- 3. ModuleNotFoundError: No module named 'wordcloud'
- 4. TypeError: 'int' object is not iterable
- 5. ModuleNotFoundError: No module named 'pandas'
- 6. ImportError: Missing optional dependency 'xlrd'. Install xlrd >= 1.0.0 for Excel support Use pip or conda to install xlrd.
- 7. 'gbk' codec can't encode character '\xa0' in position 128: illegal multibyte sequence
- 8. AttributeError: 'DataFrame' object has no attribute 'sort_value'
- 9. AttributeError: module 'pandas' has no attribute 'values_counts'
- 10. AttributeError: 'Series' object has no attribute 'sort'
说明:
很多Error是我在实现时遇到的问题,以及解决方案,当然方法肯定不一定一样,但是只要能解决就是最好的,不是嘛!
电影数据爬取阶段
教程参考
基于以上教程,稍作修改:
- 利用python爬取 豆瓣电影 Top 250
网页电影信息 - 保存数据到excel中
- 保存数据到mysql数据库中
- 下方error都是在项目实现中遇到的一些bug
- 爬虫项目实现效果图如下:
数据爬取阶段项目代码
# encoding=gbk # 页面编码格式
from bs4 import BeautifulSoup # 网页解析,获取数据
import re # 正则表达式,与文字匹配
import xlwt # 制定URL,获取网页数据
import urllib.request, urllib.error # 进行excel操作
import MySQLdb # 使用mysql数据库
import logging # 使用log日志
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') #改变标准输出的默认编码
#根据url获取html
def askURL(url):
head = { # 模拟浏览器头部信息,向服务器发送消息
"User-Agent": " Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 83.0.4103.116Safari / 537.36"
}
html=''
request = urllib.request.Request(url, headers=head)
try:
response = urllib.request.urlopen(request)
html = response.read()#获取网页内容
print ("%s crawl success" % url)
except urllib.error.URLError as e:
print ("%s crawl fail" % url)
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
return html
#根据网页信息 利用正则表达式进行数据解析
def getData(baseurl):
datalist = []
for i in range(0, 10): #网页翻页
findLink=re.compile(r'<a href="(.*?)">') #找到影片详情链接
findImgSrc=re.compile(r'<img.*src="(.*?)"',re.S) #找到影片图片
findTitle=re.compile(r'<span class="title">(.*)</span>') #找到片名
findRating=re.compile(r'<span class="rating_num" property="v:average">(.*)</span>') #找到评分
findJudge=re.compile(r'<span>(\d*)人评价</span>') #找到评价人数
findInq=re.compile(r'<span class="inq">(.*)</span>')#找到概况
findBd=re.compile(r'<p class="">(.*?)</p>',re.S) #找到影片相关内容:导演,主演,年份,地区,类别
remove=re.compile(r' |\n|</br>|\.*') #去掉无关内容
url = baseurl+'?start='+str(i * 25)
html = askURL(url) # 保存爬取的网页源码
soup = BeautifulSoup(html, "html.parser")# 逐一解析数据
for item in soup.find_all('div', class_='item'):
#print(item) # 测试
data = [] # 保存
item = str(item) # 转换成字符串
# re库正则表达式来查找指定字符串,形成列表
Link = re.findall(findLink, item)[0] # 链接
# print(Link)
data.append(Link)
ImaSrc = re.findall(findImgSrc, item)[0] # 图片链接
# print(ImaSrc)
data.append(ImaSrc)
Title = re.findall(findTitle, item)[0] # 片名:可能只有一个中文名,没有外译名字
data.append(Title)#添加片名
Rating = re.findall(findRating, item)[0] # 评分
data.append(Rating)
Judge = re.findall(findJudge, item)[0] # 评价人数
data.append(Judge)
Inq = re.findall(findInq, item) # 概述
if len(Inq) != 0:
Inq = Inq[0].replace("。", "") # 去掉句号
data.append(Inq)
else:
data.append(" ") # 留空
Bd = re.findall(findBd, item)[0] # 相关内容
temp = re.search('[0-9]+.*\/?', Bd).group().split('/')
year, country, category = temp[0], temp[1], temp[2] # 得到年份、地区、类型
data.append(year)
data.append(country)
data.append(category)
#print(data)
datalist.append(data) # 把处理好的一部电影信息放入datalist
return datalist
#保存数据:写入excel
def saveData(datalist, savepath):
print("save:豆瓣电影Top250 to excel")
book = xlwt.Workbook(encoding="utf-8") # 创建workbook对象
sheet = book.add_sheet('豆瓣电影Top250', cell_overwrite_ok=True) # 创建工作表
# 制作表头
col = ("电影详情链接", "图片链接", "中文名", "评分", "评价数", "概述", "上映年份","制片国家","类型")
for i in range(0, len(col)):
sheet.write(0, i, col[i])
for i in range(0, len(datalist)):
print("第%d条" %(i+1))
data = datalist[i]
for j in range(0, len(col)):
sheet.write(i + 1, j, data[j])
book.save(savepath) # 保存
print("The data has been successfully saved to the excel")
#保存数据:写入数据库
def saveData2DB(datalist, dbpath):
print("save:豆瓣电影Top250 to database")
try:
print("start db.connect")
conn=MySQLdb.connect(host="localhost",port=int(3306),user="root",password="root",db="test",charset="utf8")# 建立数据库连接
cursor=conn.cursor() # 获取游标对象
print("Successfully connected to the database")
except Exception as e:
print(e)
logging.error("Database connection failed")
return False;
#创建数据库,如果数据库已经存在,注意主键不要重复,否则出错
try:
print("start db.createTable")
cursor.execute("DROP TABLE IF EXISTS movie250")
sql=""" CREATE TABLE movie250(
info_link char(250),
pic_link char(250),
cname char(250),
score char(250),
rated char(250),
introduction char(250),
year_release char(250),
country char(250),
category char(250))"""
cursor.execute(sql)
print("Successfully db.createTable")
except:
print('数据库已存在!')
#插入数据
try:
print("start db.insert")
for data in datalist:
for index in range(len(data)):
data[index] = '"' + data[index] + '"'
sql = '''
insert into movie250(
info_link, pic_link, cname, score,rated, introduction,year_release,country,category )
values(%s)''' % ",".join(data)
print(sql)
cursor.execute(sql)
print('insert ok')
conn.commit()
print("The data has been successfully saved to the database")
except Exception as e:
print(e)
print("db insertion failed")
finally:
cursor.close()
conn.close()
#主函数
if __name__=="__main__":
print ("开始爬取......")
baseurl='https://movie.douban.com/top250'
# html=askURL(baseurl)
# print(html)
datalist=getData(baseurl)
# print(datalist)
savepath=u'./豆瓣电影Top250.xls'
saveData(datalist,savepath)
# dbpath='' # 数据库在方法里面配置,这里相当于无用
# saveData2DB(datalist,dbpath)
"""
本次实现:
1.数据爬取
2.数据存储到excel
3.数据存储到mysql
"""
1. ModuleNotFoundError: No module named ‘xlwt’
利用豆瓣镜像,安装一下
python -m pip install xlwt -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
2. AttributeError: module ‘urllib’ has no attribute ‘request’
import urllib
时仅仅导入该包,其他什么都做不了。因此需要我们导入的时候这样导入:
import urllib.request
3. UnboundLocalError: local variable ‘xxx’ referenced before assignment
主要是因为没有让解释器清楚变量是全局变量还是局部变量。
4. SyntaxError: invalid syntax
意思是 语法错误;
比如:空格,tab
5. NameError: name ‘saveData’ is not defined
名称错误:未定义名称“saveData”
6. IndexError: list index out of range
索引器错误:列表索引超出范围
7. ModuleNotFoundError: No module named ‘MySQLdb’
问题:未安装mysql数据库模块,
python2和python3在数据库模块支持这里存在区别,python2是mysqldb,而到了python3就变成mysqlclient,所以需要根据版本来选择
python -m pip install mysqldb #python2
python -m pip install mysqlclient #python3
8. UnicodeEncodeError: ‘charmap’ codec can’t encode characters in position 285-290: character maps to
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')
#改变标准输出的默认编码
9. (2019, “Can’t initialize character set utf-8 (path: compiled_in)”)
数据库编码设置
# 建立数据库连接
conn=MySQLdb.connect(host="localhost",
port=int(3306),
user="root",
password="root",
db="test",
charset="utf8")
10. ‘gbk’ codec can’t encode character ‘\xa0’ in position 339: illegal multibyte sequence
原来是print()函数自身有限制,不能完全打印所有的unicode字符。
解决方法同error 8
11. (1136, “Column count doesn’t match value count at row 1”)
sql语句中,前后列数不等造成的
比如这个项目中,未向数据表中添加ID
12. TypeError: object of type ‘NoneType’ has no len()
定义的函数没有返回值,加上返回值即可
一般我们在写函数时都会return要返回的值
在python中如果不写return,就默认return None
13. TypeError: can’t concat str to bytes
bytes类型的不能直接和字符串相“+”,用str()将bytes类型部分转成字符串
信息图像化阶段
信息图像化阶段:图像化展示爬取的数据
本阶段主要实现以下内容:
- mysql数据查询
- excel数据查询
- 词云制作
- python图像展示
- 线形图
- 柱状图
部分效果图
基于mysql的本阶段代码
# encoding=gbk
from bs4 import BeautifulSoup # 网页解析,获取数据
import re # 正则表达式,与文字匹配
import xlwt # 制定URL,获取网页数据
import sqlite3 # 进行sqlite数据库操作
import urllib.request, urllib.error # 进行excel操作
import MySQLdb # 使用mysql数据库
import logging # 使用log日志
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') #改变标准输出的默认编码
from collections import Counter # 获取词频
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import jieba #分词
from matplotlib import pyplot as plt #绘图,数据可视化
from wordcloud import WordCloud #词云
from PIL import Image #图片处理
import numpy as np #矩阵运算
#根据url获取html
def askURL(url):
head = { # 模拟浏览器头部信息,向服务器发送消息
"User-Agent": " Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 83.0.4103.116Safari / 537.36"
}
html=''
request = urllib.request.Request(url, headers=head)
try:
response = urllib.request.urlopen(request)
html = response.read()#获取网页内容
print ("%s crawl success" % url)
except urllib.error.URLError as e:
print ("%s crawl fail" % url)
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
return html
#根据网页信息 利用正则表达式进行数据解析
def getData(baseurl):
datalist = []
for i in range(0, 1):
findLink=re.compile(r'<a href="(.*?)">') #找到影片详情链接
findImgSrc=re.compile(r'<img.*src="(.*?)"',re.S) #找到影片图片
findTitle=re.compile(r'<span class="title">(.*)</span>') #找到片名
findRating=re.compile(r'<span class="rating_num" property="v:average">(.*)</span>') #找到评分
findJudge=re.compile(r'<span>(\d*)人评价</span>') #找到评价人数
findInq=re.compile(r'<span class="inq">(.*)</span>')#找到概况
findBd=re.compile(r'<p class="">(.*?)</p>',re.S) #找到影片相关内容:导演,主演,年份,地区,类别
remove=re.compile(r' |\n|</br>|\.*') #去掉无关内容
url = baseurl+'?start='+str(i * 25)
html = askURL(url) # 保存爬取的网页源码
soup = BeautifulSoup(html, "html.parser")# 逐一解析数据
for item in soup.find_all('div', class_='item'):
#print(item) # 测试
data = [] # 保存
item = str(item) # 转换成字符串
# re库正则表达式来查找指定字符串,形成列表
Link = re.findall(findLink, item)[0] # 链接
# print(Link)
data.append(Link)
ImaSrc = re.findall(findImgSrc, item)[0] # 图片链接
# print(ImaSrc)
data.append(ImaSrc)
Title = re.findall(findTitle, item)[0] # 片名:可能只有一个中文名,没有外译名字
data.append(Title)#添加片名
Rating = re.findall(findRating, item)[0] # 评分
data.append(Rating)
Judge = re.findall(findJudge, item)[0] # 评价人数
data.append(Judge)
Inq = re.findall(findInq, item) # 概述
if len(Inq) != 0:
Inq = Inq[0].replace("。", "") # 去掉句号
data.append(Inq)
else:
data.append(" ") # 留空
Bd = re.findall(findBd, item)[0] # 相关内容
temp = re.search('[0-9]+.*\/?', Bd).group().split('/')
year, country, category = temp[0], temp[1], temp[2] # 得到年份、地区、类型
data.append(year)
data.append(country)
data.append(category)
#print(data)
datalist.append(data) # 把处理好的一部电影信息放入datalist
return datalist
#保存数据:写入excel
def saveData(datalist, savepath):
print("save:豆瓣电影Top250 to excel")
book = xlwt.Workbook(encoding="utf-8") # 创建workbook对象
sheet = book.add_sheet('豆瓣电影Top250', cell_overwrite_ok=True) # 创建工作表
# 制作表头
col = ("电影详情链接", "图片链接", "中文名", "评分", "评价数", "概述", "上映年份","制片国家","类型")
for i in range(0, len(col)):
sheet.write(0, i, col[i])
for i in range(0, len(datalist)):
print("第%d条" %(i+1))
data = datalist[i]
for j in range(0, len(col)):
sheet.write(i + 1, j, data[j])
book.save(savepath) # 保存
print("The data has been successfully saved to the excel")
#保存数据:写入数据库
def saveData2DB(datalist, dbpath):
print("save:豆瓣电影Top250 to database")
try:
print("start db.connect")
conn=MySQLdb.connect(host="localhost",port=int(3306),user="root",password="root",db="test",charset="utf8")# 建立数据库连接
cursor=conn.cursor() # 获取游标对象
print("Successfully connected to the database")
except Exception as e:
print(e)
logging.error("Database connection failed")
return False;
#创建数据库,如果数据库已经存在,注意主键不要重复,否则出错
try:
print("start db.createTable")
cursor.execute("DROP TABLE IF EXISTS movie250")
sql=""" CREATE TABLE movie250(
info_link char(250),
pic_link char(250),
cname char(250),
score char(250),
rated char(250),
introduction char(250),
year_release char(250),
country char(250),
category char(250))"""
cursor.execute(sql)
print("Successfully db.createTable")
except:
print('数据库已存在!')
#插入数据
try:
print("start db.insert")
for data in datalist:
for index in range(len(data)):
data[index] = '"' + data[index] + '"'
sql = '''
insert into movie250(
info_link, pic_link, cname, score,rated, introduction,year_release,country,category )
values(%s)''' % ",".join(data)
print(sql)
cursor.execute(sql)
print('insert ok')
conn.commit()
print("The data has been successfully saved to the database")
except Exception as e:
print(e)
print("db insertion failed")
finally:
cursor.close()
conn.close()
#从数据库查询movie详细信息
def movie():
datalist = []
conn=MySQLdb.connect(host="localhost",port=int(3306),user="root",password="root",db="test",charset="utf8")# 建立数据库连接
cursor = conn.cursor()
sql = "select * from movie250"
#print(sql)
cursor.execute(sql) # 是否返回数据呢?
data = cursor.fetchall() # 获取所有记录列表
#print(data)
for item in data:
#print(item)
datalist.append(item)
cursor.close()
conn.close()
#print(datalist)
return datalist
#从数据库查询评分高低
def score():
score = [] # 评分
num = [] # 每个评分所统计出的电影数量
score2 = [] # 评分
num2 = [] # 每个评分所统计出的电影数量
res={}
datalist=[] # 用于返回数据
conn=MySQLdb.connect(host="localhost",port=int(3306),user="root",password="root",db="test",charset="utf8")# 建立数据库连接
cursor = conn.cursor()
sql = "select score,count(score) from movie250 group by score" #分组查询评分
cursor.execute(sql)
data = cursor.fetchall()
#print(data)
for item in data:
#print(item)
score.append(str(item[0]))
num.append(item[1])
for k, v in zip(score, num):
res.update({k: v, },)
#print(res)
sql2="select year_release,count(year_release) from movie250 group by year_release" #分组查询该年份出品数量
cursor.execute(sql2)
data2 = cursor.fetchall()
#print(data2)
for item2 in data2:
#print(item2)
score2.append(str(item2[0]))
num2.append(item2[1])
datalist.append(res)
cursor.close()
conn.close()
return datalist
def chiyun ():
#准备词云所需的文字(词)
conn=MySQLdb.connect(host="localhost",port=int(3306),user="root",password="root",db="test",charset="utf8")# 建立数据库连接
cursor = conn.cursor()
sql = 'select category from movie250'# 查询电影类别
# sql = 'select introduction from movie250'
cursor.execute(sql)
data = cursor.fetchall()
text = ""
for item in data:
#print(item)
text = text + item[0]
#print(item[0])
#print(text)
cursor.close()
conn.close()
#分词
cut = jieba.cut(text)
string = ' '.join(cut)
print(string)
print(len(string))
img = Image.open(r'.\img\1.jpg')#打开遮罩图片
img_array = np.array(img) #将图片转换为数组
wc = WordCloud(
background_color='white',
mask=img_array,
font_path="msyh.ttc" #字体所在位置
)
wc.generate_from_text(string) #
#绘制图片
fig = plt.figure(1)
plt.imshow(wc)
plt.axis('off') #是否显示坐标轴
plt.show() #显示生成的词云图片
#输出词云图片到文件
plt.savefig(r'.\img\a.jpg',dpi=500)
#上映年度分布图
def movieShow():
datalist = movie()
#print(datalist)
############################################################################
#上映年度分布图 --- 线形图
data=[]
for item in datalist:
data.append(item[6][0:4])
data_counts = Counter(data)#获取词频
#print(data_counts)
data_list = list(data_counts.items()) #键值对转化成了元祖
#print(data_list)
data_list.sort(key=lambda x:x[0], reverse=False) #按第一个元素升序排序
#print(data_list)
x=[]
y=[]
for item in data_list:
x.append(item[0][0:4]) # 截取第一个元素到第四个
y.append(item[1])
x=np.array(x)
y=np.array(y)
print(x)
print(y)
plt.figure()
plt.title("上映年度分布图")
plt.xlabel("年份")
plt.ylabel("数量")
plt.plot(x,y,'y-')
############################################################################
#上映年度分布图 --- 柱状图
plt.figure()
plt.title("上映年度分布图")
plt.xlabel("年份")
plt.ylabel("数量")
plt.bar(x,y,fc='y')
#将横坐标旋转45度(默认是垂直竖放),且坐标尾部对齐至轴(默认旋转后是中心点对齐轴)
ax=plt.gca()
ax.set_xticklabels(x,rotation=45,ha="right")
plt.rcParams['font.sans-serif'] = ['SimHei']# 可以plt绘图过程中中文无法显示的问题
plt.show()
#评分分布图
def scoreShow ():
datalist = score()
print(datalist)
############################################################################
#评分分布图 --- 线形图
x=[]
y=[]
for item in datalist:
datalist = item
print(datalist)
for key,values in datalist.items():
x.append(key)
y.append(values)
print(x)
print(y)
plt.figure()
plt.title("评分分布图")
plt.xlabel("评分")
plt.ylabel("数量")
plt.plot(x,y,'r-')
# ############################################################################
# #评分分布图 --- 柱状图
plt.figure()
plt.title("评分分布图")
plt.xlabel("评分")
plt.ylabel("数量")
plt.bar(x,y,color='rgb')
#将横坐标旋转45度(默认是垂直竖放),且坐标尾部对齐至轴(默认旋转后是中心点对齐轴)
ax=plt.gca()
ax.set_xticklabels(x,rotation=45,ha="right")
plt.rcParams['font.sans-serif'] = ['SimHei']# 可以plt绘图过程中中文无法显示的问题
plt.show()
#主函数
if __name__=="__main__":
# movie()
# score()
# chiyun()
# movieShow()
scoreShow()
"""
本次实现:
1.从mysql中查询数据
2.词云制作
3.python图像展示数据
4.线形图绘制
5.柱状图绘制
"""
基于excel的本阶段代码
#encoding=gbk
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') #改变标准输出的默认编码
data=pd.read_excel(r".\豆瓣电影Top250.xls")
#按照上映年份进行升序排列
#data.sort_values(by="上映年份",ascending=True,inplace=True)
#上映年度分布图
def movieShow ():
#上映年度分布图 --- 线形图
df_data = data['上映年份']
print(df_data)
data_counts = data['上映年份'].value_counts()#获取词频
print(data_counts)
df_data_counts = pd.DataFrame(data_counts) #将词频结果转成DataFrame格式
#print(df_data_counts)
#print(df_data_counts.index.values.tolist()) #把词转成列表
#print(df_data_counts['上映年份'].tolist()) #把词出现的次数转成列表
data_dict = dict(zip(df_data_counts.index.values.tolist(), df_data_counts['上映年份'].tolist())) #转成字典
#print(data_dict)
data_list = list(data_dict.items()) #键值对转化成了元祖
data_list.sort(key=lambda x:x[0], reverse=False) #按第一个元素升序排序
print(data_list)
x=[]
y=[]
for item in data_list:
x.append(item[0][0:4]) # 截取第一个元素到第四个
y.append(item[1])
x=np.array(x)
y=np.array(y)
print(x)
print(y)
plt.figure()
plt.title("上映年度分布图")
plt.xlabel("年份")
plt.ylabel("数量")
plt.plot(x,y,'y-')
#将横坐标旋转45度(默认是垂直竖放),且坐标尾部对齐至轴(默认旋转后是中心点对齐轴)
ax=plt.gca()
ax.set_xticklabels(x,rotation=45,ha="right")
############################################################################
#上映年度分布图 --- 柱状图
plt.figure()
plt.title("上映年度分布图")
plt.xlabel("年份")
plt.ylabel("数量")
plt.bar(x,y,fc='r')
ax=plt.gca()
ax.set_xticklabels(x,rotation=45,ha="right")
plt.rcParams['font.sans-serif'] = ['SimHei']# 可以plt绘图过程中中文无法显示的问题
plt.show()
#评分分布图
def scoreShow ():
#评分分布图 --- 线形图
scores = data['评分']
#print(scores)
score_counts = data['评分'].value_counts()#获取词频
#print(score_counts)
df_data_counts = pd.DataFrame(score_counts) #将词频结果转成DataFrame格式
data_dict = dict(zip(df_data_counts.index.values.tolist(), df_data_counts['评分'].tolist())) #转成字典
#print(data_dict)
data_list = list(data_dict.items()) #键值对转化成了元祖
data_list.sort(key=lambda x:x[0], reverse=False) #按第一个元素升序排序
print(data_list)
x=[]
y=[]
for item in data_list:
print(item)
x.append(''+str(item[0])+'') # 为何这样写:下面有解释
# x.append(item[0])
y.append(item[1])
np.array(x)
np.array(y)
print(x)
print(y)
plt.figure()
plt.title("评分分布图")
plt.xlabel("评分")
plt.ylabel("数量")
plt.plot(x,y,'r-')
############################################################################
#评分分布图 --- 柱状图
plt.figure()
plt.title("评分分布图")
plt.xlabel("评分")
plt.ylabel("数量")
plt.bar(x,y,color='rgb')
plt.rcParams['font.sans-serif'] = ['SimHei']# 可以plt绘图过程中中文无法显示的问题
plt.show()
if __name__ == "__main__":
# movieShow()
scoreShow()
"""
本次实现:
1.从excel中查询数据
2.python图像展示数据
3.线形图绘制
4.柱状图绘制
==========================================
x.append(''+str(item[0])+'')的解释:
可以替换为 x.append(item[0])尝试一下
mysql:中score最后输出格式
['8.3', '8.4', '8.5', '8.6', '8.7', '8.8', '8.9', '9.0', '9.1', '9.2', '9.3', '9.4', '9.5', '9.6', '9.7']
[1, 3, 12, 26, 43, 40, 34, 22, 21, 18, 18, 5, 4, 2, 1]
excel:中score最后输出格式
[8.3, 8.4, 8.5, 8.6, 8.7, 8.8, 8.9, 9.0, 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7]
[1, 3, 12, 26, 43, 40, 34, 22, 21, 18, 18, 5, 4, 2, 1]
"""
1. cursor.execute(sql)的返回值问题
data = cursor.execute(sql) # data=数据个数(250)
但是我们需要的是data=详细数据,所以我们使用
cursor.execute(sql) # 是否返回数据呢?
data = cursor.fetchall()# 获取所有记录列表
2. ModuleNotFoundError: No module named ‘jieba’
分词模块,从豆瓣下载,速度飞快
python -m pip install jieba -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
3. ModuleNotFoundError: No module named ‘wordcloud’
词云,从豆瓣下载,速度飞快
python -m pip install wordcloud -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
4. TypeError: ‘int’ object is not iterable
含义:'int’对象不可迭代
解决办法:不能直接用int进行迭代,而必须加个range
如:for i in range(ix):
5. ModuleNotFoundError: No module named ‘pandas’
python -m pip install pandas -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
6. ImportError: Missing optional dependency ‘xlrd’. Install xlrd >= 1.0.0 for Excel support Use pip or conda to install xlrd.
python -m pip install xlrd -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
7. ‘gbk’ codec can’t encode character ‘\xa0’ in position 128: illegal multibyte sequence
编码格式:这种还是遇到的比较多的,但是要注意页面编码格式和获取的数据编码格式,他们不同是可以的,当然一样最好。
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')
#改变标准输出的默认编码
8. AttributeError: ‘DataFrame’ object has no attribute ‘sort_value’
- 由于安装了较高版本的pandas,官方移除了一些不推荐使用的方法函数,
- python版本问题,由于python的升级和修改很多东西在不断被替换
- 变量格式问题,是:字典,列表,还是元祖,不同的格式,它的子方法不同___
9. AttributeError: module ‘pandas’ has no attribute ‘values_counts’
- python版本问题,由于python的升级和修改很多东西在不断被替换
- 变量格式问题,是:字典,列表,还是元祖,不同的格式,它的子方法不同
10. AttributeError: ‘Series’ object has no attribute ‘sort’
- python版本问题,由于python的升级和修改很多东西在不断被替换
- 变量格式问题,是:字典,列表,还是元祖,不同的格式,它的子方法不同