Python学习的第二天

1. Python库中的GUI界面 ——turtle

知识小结:
1. 导入turtle as 是给起一个别名

import turtle as t

2. 画笔运动命令
  • t.forward(distance)——向当前画笔方向移动distance像素长。简写为t.fd(distance)。
  • t.backward(distance)——向当前画笔相反方向移动distance像素长度
  • t.right(degree)——顺时针移动degree°。简写为t.rt(distance)。
  • t.left(degree)——逆时针移动degree°。简写为t.lt(degree)。
  • t.pendown()——移动时绘制图形,缺省时也为绘制。画笔落下,留下痕迹。简写为t.pd()。
  • t.penup()——移动时不绘制图形,提起笔,用于另起一个地方绘制时用。画笔抬起,不留痕迹。
  • t.goto(x,y)——将画笔移动到坐标为x,y的位置
  • t.speed(speed)——画笔绘制的速度范围[0,10]整数
  • t.circle()——画圆,半径为正(负),表示圆心在画笔的左边(右边)画圆
3. 画笔控制命令
  • t.pensize(width)——绘制图形时的宽度
  • t.pencolor()——画笔颜色
  • t.fillcolor(colorstring)——绘制图形的填充颜色
  • t.color(color1, color2)——同时设置pencolor=color1, fillcolor=color2
  • t.filling()——返回当前是否在填充状态
  • t.begin_fill()——准备开始填充图形
  • t.end_fill()——填充完成
  • t.hideturtle()——隐藏箭头显示
  • t.showturtle()——与hideturtle()函数对应
4. 全局控制命令
  • t.clear()——清空turtle窗口,但是turtle的位置和状态不会改变
  • t.reset()——清空窗口,重置turtle状态为起始状态
  • t.undo()——撤销上一个turtle动作
  • t.isvisible()——返回当前turtle是否可见
  • stamp()——复制当前图形
  • t.write(s[,font=("font-name",font_size,"font_type")])——写文本,s为文本内容,font是字体的参数,里面分别为字体名称,大小和类型;font为可选项, font的参数也是可选项
5. 例子——绘制NEUSOFT
# Python库中的GUI界面  --》 turtle
# turtle的简单使用
# 导入turtle as 是给起一个别名
import turtle as t
# 设置画笔的大小 10px
t.pensize(10)
# 设置颜色
t.color('blue')
# 绘制 NEUSOFT
# 水平左移
# 绘制N
# 抬笔
t.penup()
t.goto(-260,0)
# 画笔落下留下痕迹
t.pd()
t.left(90)
t.forward(80)
t.right(145)
# 简写
t.fd(100)
t.lt(145)
t.fd(80)
# 绘制E
# right(degree)是顺时针,left(degree)是逆时针移动degree
# forward(distance)向着某方向画distance
# t.pd()显示画笔
t.penup()
t.goto(-100,0)
t.pd()
t.left(90)
t.forward(50)
t.left(-90)
t.forward(80)
t.rt(90)
t.forward(50)
t.penup()
t.goto(-150,40)
t.pd()
t.forward(50)
# 绘制U
t.penup()
t.goto(-50,80)
t.pd()
t.right(90)
t.forward(50)
t.penup()
# t.goto(-50,20)
t.pd()
t.circle(30,180)
t.pd()
t.forward(50)

# 绘制S
t.penup()
t.goto(90,60)
t.pd()
t.circle(21,270)
# t.left(45)
t.circle(-21,270)
# 绘制O
t.penup()
t.goto(187,40)
t.pd()
# # 度数
t.circle(35,360)
# 绘制F
t.penup()
t.goto(260,80)
t.pd()
t.left(90)
t.forward(50)
t.left(90)
t.forward(80)
t.penup()
t.goto(210,40)
t.pd()
t.left(90)
t.forward(50)
# 绘制T
t.penup()
t.goto(290,80)
t.pd()
t.forward(70)
t.goto(325,80)
t.right(90)
t.forward(80)
# 让GUI界面一直显示,所有执行的代码要写在此函数之前
t.done()

效果图:
绘制图.PNG

2. Python常用数据类型

1. 列表

小结:与C语言中的数组很像,只不过可以存储不同类型的数据。优点:灵活;缺点:效率低。
定义方式 []
Fruits_name = ['苹果','香蕉','葡萄','水蜜桃']

  • 列表的访问——列表名[索引]
    print(Fruits_name[2])
  • 添加append
    Fruits_name.append('梨')
  • 修改
    Fruits_name[1] = '橘子'
  • 删除
    del Fruits_name[1]
    eg:
# Python常用数据类型
# 列表:与C语言中的数组很像,只不过可以存储不同类型的数据
# 优点:灵活;缺点:效率低
# 定义方式 []
Fruits_name = ['苹果','香蕉','葡萄','水蜜桃']
# 输出
print(Fruits_name)
# 遍历
for hero in Fruits_name:
    print(hero)
# 常见操作
# 1.列表的访问
# 列表名[索引]
print(Fruits_name[2])
# 2.添加append
Fruits_name.append('梨')
print('添加后的列表',Fruits_name)
# 3.修改
Fruits_name[1] = '橘子'
print('修改后后的列表:',Fruits_name)
# 4.删除
del Fruits_name[1]
print('删除后的列表:',Fruits_name)
# 练习
# 创建[1,2,3,...10]这样一个数字列表
# 1.创建空列表
# 2.使用for循环,在循环中添加元素值
list = []
for i in range(1,11):
    list.append(i)
print(list)
image.png

2. 字符串

定义形式 ''(单引号)""(双引号)

  • 切片,对序列截取一部分的操作,适用于列表
name = 'abcdefg'
print(name[1])
print(name[1:4])
# a c e g
print(name[0:7:2])
# # 全切片的时候可以省略初始和终止位置
print(name[::2])
image.png
  • 常用方法——去两端空格
# 去两端空格
name = ' abcdefg '
# 查看序列内元素的个数 Len()
print(len(name))
name = name.strip()
print('去空格之后',len(name))
image.png
  • 替换
price = '¥999'
price = price.replace('¥','$')
print(price)
image.png
  • 列表变成字符串的方法——join
li = ['a','b','c','d']
a = ''.join(li)
print(a)
print(type(a))
image.png

3. 元组——tuple

元组和列表很像,只不过元组不可以修改。
定义()

a = ('zhangsan','lisi','wangwu',1000)
print(a)
print(type(a))
# 访问
print(a[1])
# 修改:不可以修改元组里面的
# a[3] = 'zhaoliu'——错误
# 关于元组需要注意的是
# b = ('lisi') #是不是元组,不是
# c = (1000) #是不是元组,不是
b = ('lisi',) #是不是元组,是
c = (1000,) #是不是元组,是
print(type(b))
print(type(c))
image.png

4. 字典——dict

key-value数据结构
定义形式 {}

info = {'name':'李四','age':34,'addr':'重庆市渝北区'}
print(len(info))
print(info)
# 1.字典的访问
print(info['name'])
# 2.修改
info['addr'] = '北京市朝阳区'
print('修改后字典',info)
# 3.增加
info['sex'] = 'female'
print('增加后字典',info)
# 获取字典中所有的键
print(info.keys())
# 获取字典中所有的z值
print(info.values())
# 获取字典中所有的key-value
print(info.items())
d = [('name', '李四'), ('age', 34), ('addr', '北京市朝阳区'), ('sex', 'female')]
d1 = dict(d)
print(d1)
# 遍历字典
# for x in info.items():
#     print(x)
for x,v in info.items():
    print(x,v)
image.png

5. 集合

无序,不重复

set1 = {'zhangsan','lisi',222}
print(type(set1))
# 遍历
for x in set1:
    print(x)
image.png

6. 列表的排序

li = []
for i in range(10):
    li.append(i)
print(li)
from random import shuffle
shuffle(li)
print('随机打乱的列表',li)
li.sort()
print('排序后的列表',li)
li.sort(reverse=True)
print('排序后的列表',li)
image.png

7. 列表的排序——函数

stu_info = [
    {"name":'zhangsan',"age":18},
    {"name":'lisi',"age":30},
    {"name":'wangwu',"age":99},
    {"name":'tiaqi',"age":3},
]
print('排序前',stu_info)
# def 函数名(参数):
#     函数体
def sort_by_age(x):
    return x['age']
# key = 函数名  --按照什么进行排序
# 根据年龄大小进行正序排序
# stu_info.sort(key=)
stu_info.sort(key=sort_by_age,reverse = True)
print('排序后',stu_info)
image.png
name_info_list = [
    ('张三',4500),
    ('李四',9900),
    ('王五',2000),
    ('赵六',5500),
]
# 根据元组第二个元素进行正序排序
print('排序前',name_info_list)
def sort_by_second(x):
    return x[1]
name_info_list.sort(key=sort_by_second,reverse=False)
print('排序后',name_info_list)
image.png

3. 文件本地读取

  • Python中使用open内置函数进行文件读取
f = open(file='./novel/threekingdom.txt',mode='r',encoding='utf-8')
data = f.read()
f.close()
# data = open(file='./novel/threekingdom.txt',mode='r',encoding='utf-8').read()
print(data)
# with as 上下文管理器 ,不用手动关闭流
with open('./novel/threekingdom.txt','r',encoding = 'utf-8') as f:
    data = f.read()
    print(data)
image.png
  • 写入
txt = 'i like python'
with open('python.txt','w',encoding='utf-8') as f:
    f.write(txt)
text = """


    
    Title


重庆师范欢迎你

""" print(text) with open('chongqingshifan.html','w',encoding='utf-8') as f: f.write(text)
image.png

image.png
  • 网页间调用
# test6
def say_hello(name):
    print('hello,{}'.format(name))
# test
# 导入test6板块
import test6
test6.say_hello("喵喵")
image.png

4. 中文分词 jieba

安装环境

  • 在JetBrains PyCharm 2019.1.1 x64的settings中搜索安装jieba
  • 在Terminal中通过pip install jieba安装
    中文分词示例一:
import jieba
# 三种分词模式
seg = '我来到了重庆'
# 精确模式
seg_list = jieba.lcut(seg)
print(seg_list)
# 全模式  找出所有可能的分词结果  冗余性大
seg_list1 = jieba.lcut(seg,cut_all=True)
print(seg_list1)
# 搜索引擎模式
seg_list2 = jieba.lcut_for_search(seg)
print(seg_list2)
text = '小明硕士毕业于中国科学院计算所,后再日本京都大学深造'
seg_list4 = jieba.lcut(text,cut_all=True)
print(seg_list4)
# 搜索引擎模式
seg_list5 = jieba.lcut_for_search(text)
print(seg_list5)
image.png

中文分词示例二:

import jieba
# 三国演义小说分词
# 读取三国演义小说
with open('./novel/threekingdom.txt','r',encoding = 'utf-8') as f:
    words = f.read()
    print(len(words))# 字数 55万
    words_list = jieba.lcut(words)
    print(len(words_list))#分词后的词语数 35万
    print(words_list)
image.png

5. 词云的展示

安装环境

  • 在JetBrains PyCharm 2019.1.1 x64的settings中搜索安装wordcloud
  • 在Terminal中通过pip install Wordcloud安装
    词云的展示示例一:
from wordcloud import WordCloud
import jieba
import imageio
# 绘制词云
text = 'He was an old man who fished alone in a skiff in the Gulf Stream and he had gone eighty-four days now without taking a fish. In the first forty days a boy had been with him. But after forty days without a fish the boy’s parents had told him that the old man was now definitely and finally salao, which is the worst form of unlucky, and the boy had gone at their orders in another boat which caught three good fish the first week. It made the boy sad to see the old man come in each day with his skiff empty and he always went down to help him carry either the coiled lines or the gaff and harpoon and the sail that was furled around the mast. The sail was patched with flour sacks and, furled, it looked like the flag of permanent defeat.'
wc = WordCloud().generate(text)
wc.to_file('老人与海.png')
image.png

词云的展示示例二:

mask = imageio.imread('./china.jpg')
with open('./novel/threekingdom.txt','r',encoding='utf-8') as f:
    words = f.read()
    # print(len(words))#字数  55万
    words_list = jieba.lcut(words)
    # print(len(words_list)) # 分词后的词语数 35万
    print(words_list)
    # 将words_list转化成字符串
    novel_words = " ".join(words_list)
    print(novel_words)
    # WordCloud()里面设置参数
    wc = WordCloud(
        font_path='msyh.ttc',
        background_color='white',
        width=800,
        height=600,
        mask=mask
    ).generate(novel_words)
    wc.to_file('三国词云.png')
image.png

你可能感兴趣的:(Python学习的第二天)