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

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

1.turtle的簡單實(shí)用

-import turtle as t(起別名為t)

# Python標(biāo)準(zhǔn)庫中的GUI界面 (turtle)
# turtle的簡單使用
# 導(dǎo)入turtle  as 是給起一個別名
import turtle as t
# 設(shè)置畫筆的大小  10px
t.pensize(10)
#設(shè)置畫筆顏色為黃色
t.color('yellow')
# 繪制 NEUSOFT
# 水平左移
# 抬筆
t.penup()
t.goto(-260, 0)
t.pd()

# 繪制 N
t.left(90) 
t.forward(80)
t.right(145)
# 簡寫
t.fd(100)
t.lt(145)
t.fd(80)

# 繪制 O
t.penup()
t.goto(200, 40)
t.pd()

t.circle(30, 180)

# 讓gui界面一直顯示, 所有執(zhí)行的代碼要寫在此函數(shù)之前
t.done()

2.python常用數(shù)據(jù)類型

2.1字符串
# 字符串
# 定義形式   ''  ""
# 切片 對序列截取一部分的操作,適用于列表
# name = 'abcdefg'
# # name[1]
# # [起始位置:終止位置:步長] 左閉右開
# print(name[1:4])
# # a c e g
# print(name[0:7:2])
# # 全切片的時候可以省略初始和終止位置
# print(name[::2])
# 常用方法
# 去兩端空格

# name = '    abcdefg     '
# # 查看序列內(nèi)元素的個數(shù)  len()
# 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))
# 數(shù)字
2.2列表
# 列表: 與c語言中的數(shù)組很相似, 只不過可以存儲不同類型的數(shù)據(jù)
# 優(yōu)點(diǎn):靈活   ,缺點(diǎn): 效率低
# 定義方式  []
hero_name = ['魯班七號', '安琪拉', '李白', '劉備']
# 輸出
# print(hero_name)
# 遍歷
# for hero in hero_name:
#     print(hero)

# 常見操作
# 1.列表的訪問
# 列表名[索引]
print(hero_name[2])

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

# 3.修改
hero_name[1] = 1000
print('修改后的列表',hero_name)

# 4.刪除
del hero_name[1]
print('刪除后的列表',hero_name)
2.3元組
# 元組 tuple  元組和列表很像只不過元組不可以修改
# 定義  ()
# a = ('zhangsan', 'lisi', 'wangwu',1000)
# print(a)
# print(type(a))
#
# # 訪問
# print(a[1])
# # # 修改
# # a[3] = 'zhaoliu'
#
# # 關(guān)于元組需要注意的是 只有一個元素的元組
# b = ('lisi',) #是不是元組
# c = (1000,) #是不是元組
# print(type(b))
# print(type(c))
2.4字典
# 字典  dict   java  hashmap
# key-value數(shù)據(jù)結(jié)構(gòu)
# 定義形式  {}
info = {'name':'李四', 'age':34, 'addr':'重慶市渝北區(qū)'}
print(len(info))
print(info)
# 1.字典的訪問
print(info['name'])
# 2.修改
info['addr'] = '北京市朝陽區(qū)'
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', '北京市朝陽區(qū)'), ('sex', 'female')]
d1 = dict(d)
print(d1)
#  遍歷字典
for k, v in info.items():
    print(k, v)
2.5集合
# 集合
#  無序,不重復(fù)
set1 = {'zhangsan', 'lisi', 222}
#
print(type(set1))
# 遍歷
for x in set1:
    print(x)

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

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

stu_info = [
    {"name":'zhangsan', "age":18},
    {"name":'lisi', "age":30},
    {"name":'wangwu', "age":99},
    {"name":'tiaqi', "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)

# 練習(xí)
name_info_list = [
    ('張三',4500),
    ('李四',9900),
    ('王五',2000),
    ('趙六',5500),
]

4.本地文件讀取

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(file='./novel/threekingdom.txt', mode='r',encoding='utf-8') as f1:
    data1 = f1.read()
    print(data1)

3.寫入文件流

# 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)
python中使用open內(nèi)置函數(shù)進(jìn)行文件讀取

5.中文分詞和繪制詞云

使用Python做中文分詞和繪制詞云

4.1中文分詞 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.三國演義分詞

import jieba
# 讀取小說
with open(file='./novel/threekingdom.txt', mode='r',encoding='utf-8') as fs:
    words = fs.read()
    print('原字?jǐn)?shù):', len(words))
    words_list = jieba.lcut(words)
    print('分詞后字?jǐn)?shù):', len(words_list))
    print(words_list)
4.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')
老人與海詞云

②三國演義

# 三國演義小說分詞
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')
三國演義詞云
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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