python學(xué)習(xí)第二天

一、Python標準庫中的GUI界面--turtle

1.turtle 的簡單使用

  1. 繪制NEUSOFT
    ①導(dǎo)入turtle as 是給起一個別名
    ②設(shè)置畫筆大小 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為正數(shù),以左手邊為圓心,為負數(shù),以右手邊為圓心
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界面一直顯示,所有執(zhí)行的代碼要寫在此函數(shù)之前
t.done()
image.png

二、python 常用數(shù)據(jù)類型

1.列表

  1. 定義方式: [ ] ,與C語言中數(shù)組相似,只不過可以存儲不同類型的數(shù)據(jù)
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)

⑥練習(xí)
a.創(chuàng)建[1,2,3,4,5....10]數(shù)字列表
b.創(chuàng)建空列表
c.使用for循環(huán)添加

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    '
# 查看序列元素個數(shù)
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數(shù)據(jù)結(jié)構(gòu)
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.小練習(xí)
d = ([('name', '李四'), ('sex', '男'), ('age', '40'), ('addr', '重慶市')])
d1 = dict(d)
print(d1)

5.集合 set

  1. 特點:無序,不重復(fù)
set1 = {'zs', 'ls', 222}
print(type(set1))
# 遍歷
for x in set1:
    print(x)

三、掌握python常用數(shù)據(jù)類型和語法

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:
    ①函數(shù)定義:
    def 函數(shù)名(參數(shù)):
    函數(shù)體
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']
# 根據(jù)年齡排序
# key= 函數(shù)名
stu_info.sort(key= sort_by_age, reverse= True)
print('排序后:', stu_info)

③ 練習(xí)

name_info_list = [
    ('張三', 4500),
    ('李四', 9900),
    ('王五', 2000),
    ('趙六', 5500),
]
print('排序前:', name_info_list)
# 根據(jù)元組第二個元素排序
def money(x):
    return x[1]
name_info_list.sort(key= money, reverse= True)
print('排序后:', name_info_list)

四、本地文件讀取

  1. python中使用open內(nèi)置函數(shù)進行文件讀取
f = open(file='./novel/threekingdom.txt', mode='r', encoding='utf-8')
data = f.read()
f.close()
print(data)
  1. with as 上下文管理器 不用手動關(guān)閉流
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 = """<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>重慶師范歡迎你</h1>
</body>
</html>"""
print(text)
with open('chongqingshifan.html', 'w', encoding='utf-8') as f3:
    f3.write(text)

五、中文分詞 jieba

  1. 關(guān)于安裝jieba分詞庫
    指定國內(nèi)鏡像安裝
    在用戶目錄下新建pip文件夾
    新建pip.ini文件
    添加
    """
    [global]
    index-url = http://mirrors.aliyun.com/pypi/simple/
    [install]
    trusted-host=mirrors.aliyun.com
    """
    pip install jieba
  2. 關(guān)于應(yīng)用
    ①導(dǎo)入jieba分詞
import jieba
seg = "我來到北京清華大學(xué)"

② 三種分詞形式
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 = '小明碩士畢業(yè)與中國科學(xué)院計算機所,后在日本留學(xué)深造'
seg_list3 = jieba.lcut(text, cut_all=True)
print(seg_list3)
# 搜索引擎模式 先執(zhí)行精確模式,在對其長詞進行處理
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('原字數(shù):', len(words))
    words_list = jieba.lcut(words)
    print('分詞后字數(shù):', len(words_list))
    print(words_list)

六、詞云展示 wordcloud

  1. 關(guān)于安裝:
    pip install wordcloud
    本地安裝python庫
  2. 關(guān)于應(yīng)用
    ①導(dǎo)入詞云 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()
    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')
image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容