Python學(xué)習(xí)的第二天

python標(biāo)準(zhǔn)庫中的GUI界面--->>>turtle

繪制NEUSOFT:
①導(dǎo)入turtle as t ,其中t是給起個別名
②設(shè)置畫筆的大小:t.pensize(10)
③設(shè)置畫筆顏色:t.color('blue')
④抬筆:t.penup()
⑤落筆:t.pendown(),可以簡寫為t.pd()
⑥旋轉(zhuǎn):t.left(90),t.right(145)
⑦移動畫線:t.forward(80)
⑧移動位置:t.goto(-360,0)
⑨讓GUI界面一直顯示:t.done()

import turtle as t
#設(shè)置畫筆的大小  10px
t.pensize(10)
t.color('blue')
#繪制NEUSOFT
#抬筆
t.penup()
#水平左移
t.goto(-360,0)
#落筆pendown()
t.pd()
#繪制 N
#旋轉(zhuǎn)90度
t.left(90)
t.forward(80)
t.right(145)
#簡寫
t.fd(100)
t.lt(145)
t.fd(80)

#繪制E
t.penup()
t.goto(-200,0)
t.pd()
t.left(90)
t.fd(60)
t.right(90)
t.fd(80)
t.right(90)
t.fd(60)
t.penup()
t.goto(-260,40)
t.pd()
t.fd(60)

#繪制U
t.penup()
t.goto(-160,80)
t.pd()
t.right(90)
t.fd(65)
t.circle(26,180)
t.fd(65)

#繪制S
t.penup()
t.goto(-20,60)
t.pd()
# t.left(90)
t.circle(24,270)
#r是正數(shù)時,以左手為圓心畫弧,負(fù)值是以右手為圓心畫弧
#angle 是負(fù)數(shù)時代表繪制方向
t.circle(-24,270)

#繪制O
t.penup()
t.goto(100,40)
t.pd()
t.circle(45)

#繪制F
t.penup()
t.goto(150,80)
t.pd()
t.right(90)
t.fd(60)
t.penup()
t.goto(150,80)
t.pd()
t.right(90)
t.fd(90)
t.penup()
t.goto(150,40)
t.pd()
t.left(90)
t.fd(60)

#繪制T
t.penup()
t.goto(250,80)
t.pd()
t.fd(100)
t.penup()
t.goto(300,80)
t.pd()
t.right(90)
t.fd(80)
#讓GUI界面一直顯示,所有執(zhí)行的代碼要寫在此函數(shù)之前
t.done()

運(yùn)行結(jié)果:

QQ圖片20190729145937.png

python常用數(shù)據(jù)類型和語法

1、列表

與C語言中的數(shù)組很相似,只不過可以存儲不同類型的數(shù)據(jù)
優(yōu)點:靈活 缺點:效率低
①定義方式[]

hreo_name = ['魯班七號','安其拉','李白','劉備']

②輸出

print(hreo_name)

③遍歷

for hreo in hreo_name:
    print(hreo)

④列表的訪問:列表名[索引]

print(hreo_name[2])

⑤列表的添加

hreo_name.append('后裔')

⑥列表的修改

hreo_name[1] = 1000

⑦列表的刪除

del hreo_name[1]

⑧列表的排序

li = []
for i in range(10):
    li.append(i)
print(li)
from random import shuffle
shuffle(li)
print('隨機(jī)打亂的列表',li)
#reverse=True  降序
li.sort(reverse=True)
print('排序后的列表',li)

練習(xí):按年齡進(jìn)行排序

stu_info = [
    {'name':'zhangsan','age':18},
    {'name':'lisi','age':30},
    {'name':'wangwu','age':99},
    {'name':'tianqi','age':3},
            ]
print('排序前',stu_info)
# def 函數(shù)名(參數(shù)):
#     函數(shù)體
def sort_by_age(x):
    return x['age']
#key = 函數(shù)名     ----按照什么進(jìn)行排序
#根據(jù)年齡大小進(jìn)行正序排序
stu_info.sort(key = sort_by_age,reverse=True)
print('排序后',stu_info)
QQ圖片20190729191310.png

練習(xí):創(chuàng)建[1,2,3.......10]這樣的一個數(shù)字列表

#1、創(chuàng)建空列表
li = []
#2、使用for循環(huán),在循環(huán)中添加元素值
for i in range(1,11):
    li.append(i)
    i += 1
print(li)
QQ圖片20190729151046.png
2、字符串

①定義形式 ' ' ," "

name = 'abcdefg'

②切片:對序列截取一部分的操作,適用于列表
[起始位置:終止位置:步長] 左閉右開
注:全切片的時候可以省略初始和終止位置

print(name[1:4])#b c d
print(name[0:7:2])#a c e g
print(name[::2])#a c e g

③去兩端空格
查看序列內(nèi)元素的個數(shù) len()

name = 'abcdefg     '
print(len(name))
name = name.strip()
print('去空格之后:',len(name))

④替換

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

⑤列表變成字符串的方法 join

li = ['a','b','c','d']
a = '_'.join(li)
print(a)
print(type(a))#str
3、元組 tuple

元組和列表很像,只不過元組不可以修改
①定義 ()

a = ('zhangsan','lisi','wangwu',1000)

②訪問

print(a[1])

注:元組不支持修改
只有一個元素的元組:d = ('list',)

d = ('list',)#tuple
b = ('list')#str
c = (1000)#int
4、字典 dict

①數(shù)據(jù)結(jié)構(gòu)
key-value
②定義形式{}

info = {'name':'李四','age':34,'addr':'重慶市渝北區(qū)'}

③字典的訪問

print(info['name'])

④修改

info['addr'] = '北京市朝陽區(qū)'

⑤增加

info['sex'] = 'female'

⑥獲取字典中所有的鍵

print(info.keys())

⑦獲取字典中所有的值

print(info.values())

⑧獲取字典中所有的key-value

print(info.items())

⑨list轉(zhuǎn)換成字典

d = [('name', '李四'), ('age', 34), ('addr', '北京市朝陽區(qū)'), ('sex', 'female')]
d1 = dict(d)
print(d1)

⑩遍歷字典

for k,v in info.items():
    print(k,v)
6、集合 set

無序、不重復(fù)
①定義

set1 = {'zhangsan','lisi',222}

②遍歷

for x in set1:
    print(x)
7、函數(shù)

def 函數(shù)名(參數(shù)):
函數(shù)體

def say_hello(name):
    print('hello,{}'.format(name))
say_hello('重慶師范')

本地文件讀取

1、python中使用open內(nèi)置函數(shù)進(jìn)行文件讀取

f = open(file = './novel/threekingdom.txt',mode='r',encoding='utf-8')
data = f.read()
f.close()
print(data)

2、with as 上下文管理器 不用手動關(guān)閉

with open('./novel/threekingdom.txt','r',encoding='utf-8') as f:
    data = f.read()
    print(data)

寫入文件

1、寫成txt文件

txt = 'i like python!'
with open('python.txt','w',encoding='utf-8') as f:
    f.write(txt)

2、寫成html文件

text = """<!DOCTYPE html>
 <html lang="en">
 <head>
    <meta charset="UTF-8">
    <title>Title</title>
 </head>
 <body>
<h1>重慶師范歡迎你</h1>
</body>
</html>"""
print(text)
with open('chongqing.html','w',encoding='utf-8') as f:
    f.write(text)

中文分詞 jieba

安裝jieba分詞庫
指定國內(nèi)鏡像安裝:
①在用戶目錄下新建pip文件夾
②新建pip.ini文件
③添加
"""
[global]
index-url = http://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host=mirrors.aliyun.com
"""
④安裝:pip install jieba
導(dǎo)入jieba分詞:import jieba

三種分詞模式

seg = "我來到北京清華大學(xué)"

1、精確模式 :精確分詞

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

2、全模式 :找出所有可能的分詞結(jié)果 ,冗余性大

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

3、搜索引擎模式

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

4、搜索引擎模式,先執(zhí)行精確模式,在對其中的長詞進(jìn)行處理

text = '小明碩士畢業(yè)于中國科學(xué)院計算所,后在日本京都大學(xué)深造'
seg_list4 = jieba.lcut(text,cut_all=True)
print(seg_list4)
seg_list5 = jieba.lcut_for_search(text)
print(seg_list5)

三國演義小說分詞

import jieba
with open('./novel/threekingdom.txt', 'r', encoding='utf-8') as f:
    words = f.read()
    print(len(words)) # 字?jǐn)?shù)  55萬
    words_list = jieba.lcut(words)
    print(len(words_list)) # 分詞后的詞語數(shù)  35萬
    print(words_list)

詞云展示

①安裝:pip install wordcloud
②本地安裝Python庫
③導(dǎo)入詞云:from wordcloud import WordCloud
1、老人與海詞云繪制

from wordcloud import WordCloud
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')
運(yùn)行結(jié)果:
image.png

2、三國演義小說詞云繪制

from wordcloud import WordCloud
import jieba
import imageio
# 三國演義小說分詞
# 讀取三國演義小說
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)
    #將words_list轉(zhuǎn)化成字符串
    novel_words = " ".join(words_list)
    print(novel_words)
    #WordCloud()里面設(shè)置參數(shù)
    wc = WordCloud(
        font_path='msyh.ttc',
        background_color='white',
        width=800,
        height=600,
        mask=mask
    ).generate(novel_words)
    wc.to_file('./三國詞云.png')
運(yùn)行結(jié)果:
image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容