python学习第二天

一、Python标准库中的GUI界面--turtle

1.turtle 的简单使用

  1. 绘制NEUSOFT
    ①导入turtle as 是给起一个别名
    ②设置画笔大小 t.pensize()
    ③水平移动 t.goto()
    ④抬笔 t.penup()
    ⑤落笔 t.pd()
import turtle as t
t.pensize(10)
t.color('green')
# 绘制N
t.penup()
t.goto(-300, 0)
t.pd()
t.left(90)
t.forward(80)
t.right(145)
t.fd(100)
t.lt(145)
t.fd(80)
# 绘制E
t.penup()
t.goto(-170, 0)
t.pd()
t.left(90)
t.fd(50)
t.right(90)
t.fd(80)
t.right(90)
t.fd(50)
t.penup()
t.goto(-220, 40)
t.pd()
t.fd(50)
# 绘制U
t.penup()
t.goto(-145, 20)
t.pd()
t.left(90)
t.fd(60)
t.penup()
t.goto(-145, 20)
t.pd()
t.circle(-22, -180)
t.penup()
t.goto(-99, 20)
t.pd()
t.right(90)
t.right(90)
t.fd(60)
# 绘制S
t.penup()
t.goto(-35, 60)
t.pd()
t.circle(21, 270)
# r为正数,以左手边为圆心,为负数,以右手边为圆心
t.circle(-21, 270)
# 绘制O
t.penup()
t.goto(65, 40)
t.pd()
t.circle(40)
# 绘制F
t.penup()
t.goto(90, 0)
t.pd()
t.right(90)
t.left(90)
t.fd(80)
t.right(90)
t.fd(50)
t.penup()
t.goto(90, 40)
t.pd()
t.fd(50)
# 绘制T
t.penup()
t.goto(160, 80)
t.pd()
t.fd(60)
t.penup()
t.goto(190, 80)
t.pd()
t.right(90)
t.fd(80)
# 让gui界面一直显示,所有执行的代码要写在此函数之前
t.done()
python学习第二天_第1张图片
image.png

二、python 常用数据类型

1.列表

  1. 定义方式: [ ] ,与C语言中数组相似,只不过可以存储不同类型的数据
hero_name = ['鲁班七号', '安其拉', '李白', '刘备']
print(hero_name)

2.常见操作
①遍历

for hero in hero_name:
    print(hero)

②列表访问:列表[索引]

print(hero_name[2])

③添加 append

hero_name.append('后羿')
print('添加后的列表:', hero_name)

④修改

hero_name[2] = 1000
print('修改后的列表:', hero_name)

⑤删除

del hero_name[2]
print('删除后的列表:', hero_name)

⑥练习
a.创建[1,2,3,4,5....10]数字列表
b.创建空列表
c.使用for循环添加

number_list = []
for i in range(1, 11):
    number_list.append(i)
print(number_list)

2.字符串

  1. 定义形式 ' ' " " , 切片,对序列截取一部分的操作,适用于列表
name = 'abcdefg'
print(name[1:4])  # [起始位置,终止位置,步长]左闭右开
print(name[0:7:2])
# 全切片的时候可以省略初始位置和终止位置
print(name[::2])

2.常见操作
①去两端空格

name_k = '    abcdefg    '
# 查看序列元素个数
print(len(name_k))
name_k = name_k.strip()
print('去空格之后:', len(name_k))

②替换

price = '$999'
price = price.replace('$', '')
print(price)

③列表变成字符串 join

li = ['a', 'b', 'c', 'd']
a = ','.join(li)
print(a)
print(type(a))

3.元组 tuple

  1. 定义 () , 元组和列表很像,元组不可修改
ta = ('zs', 'ls', 'ww', 1000)
print(ta)
print(type(ta))
# 访问
print(ta[1])
  1. 注意:元组中只有一个元素时后面要加逗号
b = ('ls',)
c = (1000,)
print(type(b))
print(type(c))

4.字典 dict

  1. 定义 {} , key-value数据结构
info = {'name': '李四', 'sex': '男', 'age': '34'}
print(len(info))
print(info)
  1. 常见操作
# 1.访问
print(info['name'])
# 2.修改
info['age'] = '40'
print('修改后字典:', info)
# 3.增加
info['addr'] = '重庆市'
print('增加后字典:', info)
# 4.获取所有key
print(info.keys())
# 5.获取所有值
print(info.values())
# 6.获取所有key-value
print(info.items())
# 7.遍历字典
for k, v in info.items():
    print(k, v)
# 8.小练习
d = ([('name', '李四'), ('sex', '男'), ('age', '40'), ('addr', '重庆市')])
d1 = dict(d)
print(d1)

5.集合 set

  1. 特点:无序,不重复
set1 = {'zs', 'ls', 222}
print(type(set1))
# 遍历
for x in set1:
    print(x)

三、掌握python常用数据类型和语法

1.列表排序

  1. 例1:
li = []
for i in range(10):
    li.append(i)
print(li)
from random import shuffle
shuffle(li)
print('随机打乱的列表:', li)
li.sort(reverse=True)
print('排序后的列表:', li)
  1. 例2:
    ①函数定义:
    def 函数名(参数):
    函数体
stu_info = [
    {"name": 'zs', "age": '18'},
    {"name": 'ls', "age": '19'},
    {"name": 'ww', "age": '20'},
    {"name": 'tq', "age": '21'},
]
print('排序前:', stu_info)
def sort_by_age(x):
    return x['age']
# 根据年龄排序
# key= 函数名
stu_info.sort(key= sort_by_age, reverse= True)
print('排序后:', stu_info)

③ 练习

name_info_list = [
    ('张三', 4500),
    ('李四', 9900),
    ('王五', 2000),
    ('赵六', 5500),
]
print('排序前:', name_info_list)
# 根据元组第二个元素排序
def money(x):
    return x[1]
name_info_list.sort(key= money, reverse= True)
print('排序后:', name_info_list)

四、本地文件读取

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


    
    Title


重庆师范欢迎你

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

五、中文分词 jieba

  1. 关于安装jieba分词库
    指定国内镜像安装
    在用户目录下新建pip文件夹
    新建pip.ini文件
    添加
    """
    [global]
    index-url = http://mirrors.aliyun.com/pypi/simple/
    [install]
    trusted-host=mirrors.aliyun.com
    """
    pip install jieba
  2. 关于应用
    ①导入jieba分词
import jieba
seg = "我来到北京清华大学"

② 三种分词形式
a.精确模式

seg_list = jieba.lcut(seg)
print(seg_list)

b.全模式

seg_list1 = jieba.lcut(seg, cut_all=True)
print(seg_list1)

c.搜索引擎模式

seg_list2 = jieba.lcut_for_search(seg)
print(seg_list2)

d.例1:

text = '小明硕士毕业与中国科学院计算机所,后在日本留学深造'
seg_list3 = jieba.lcut(text, cut_all=True)
print(seg_list3)
# 搜索引擎模式 先执行精确模式,在对其长词进行处理
seg_list4 = jieba.lcut_for_search(text)
print(seg_list4)

e.例2:三国演义小说分词

import jieba
# 读取小说
with open(file='./novel/threekingdom.txt', mode='r',encoding='utf-8') as fs:
    words = fs.read()
    print('原字数:', len(words))
    words_list = jieba.lcut(words)
    print('分词后字数:', len(words_list))
    print(words_list)

六、词云展示 wordcloud

  1. 关于安装:
    pip install wordcloud
    本地安装python库
  2. 关于应用
    ①导入词云 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')
python学习第二天_第2张图片
image.png

③三国演义小说词云绘制

# 三国演义小说分词
mask = imageio.imread('./china.jpg')
with open('./novel/threekingdom.txt', 'r', encoding='utf-8') as f:
    words = f.read()
    words_list = jieba.lcut(words)
    print(words_list)
    novel_words = " ".join(words_list)
    print(novel_words)
    wc = WordCloud(
        font_path='msyh.ttc',
        background_color='white',
        width=800,
        height=600,
        mask=mask
    ).generate(novel_words)
    wc.to_file('三国词云.png')
python学习第二天_第3张图片
image.png

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