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

1.Python標(biāo)準(zhǔn)庫(kù)GUI界面(turtle)

1.1turtle的簡(jiǎn)單實(shí)用

turtle的簡(jiǎn)單使用
import turtle as t
t.done()
t.color('blue')
- 繪制NEUSOFT 
- 水平左移
- 抬筆
t.penup()
t.goto(-260, 0)
t.pd()

1.2繪制N

t.left(90)
t.forward(80)
t.right(145)

1.3簡(jiǎn)寫

t.fd(100)
t.lt(145)
t.fd(80)

1.4繪制O

t.penup()
t.goto(200, 40)
t.pd()
t.circle(30, 180)

1.5 繪制 S

t.penup()
t.goto(120, 50)
t.pd()

t.circle(22,270)

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

列表: 與c語(yǔ)言中的數(shù)組很相似, 只不過可以存儲(chǔ)不同類型的數(shù)據(jù)
優(yōu)點(diǎn):靈活 ,缺點(diǎn): 效率低

定義方式  []
hero_name = ['魯班七號(hào)', '安琪拉', '李白', '劉備']
 輸出
 print(hero_name)
 遍歷
for hero in hero_name:
    print(hero)

3.常見操作

3.1列表的訪問

列表名[索引]
print(hero_name[2])

3. 2添加 append

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

3.3修改

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

3.4刪除

del hero_name[1]
print('刪除后的列表',hero_name)

5.字典 (dict java hashmap)

  • key-value數(shù)據(jù)結(jié)構(gòu)
  • 定義形式 {}
info = {'name':'李四', 'age':34, 'addr':'重慶市渝北區(qū)'}
print(len(info))
print(info)

5.1字典的訪問

print(info['name'])

5.2修改

info['addr'] = '北京市朝陽(yáng)區(qū)'
print('修改后字典',info)

5.3增加

info['sex'] = 'female'
print('增加后字典',info)

5.4獲取字典中所有的鍵

print(info.keys())

5.5獲取字典中所有的z值

print(info.values())

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

print(info.items())

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

5.7遍歷字典

for k, v in info.items():
    print(k, v)

集合
  • 無序,不重復(fù)
set1 = {'zhangsan', 'lisi', 222}

print(type(set1))

  • 遍歷
for x in set1:
    print(x)

掌握python常用數(shù)據(jù)類型和語(yǔ)法
  • 列表的排序
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í)
    根據(jù)元組第二個(gè)元素進(jìn)行正序排序

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

def sort_by_grade(i):
    return i[1]

# 根據(jù)元組第二個(gè)元素進(jìn)行正序排序

name_info_list.sort(key=sort_by_grade)
print(name_info_list)

  • 例子
def say_hello(name):
    print('hello, {}'.format(name))

 say_hello('重慶師范')

6.本地文件讀取

  • python中使用open內(nèi)置函數(shù)進(jìn)行文件讀取
 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 上下文管理器 不用手動(dòng)關(guān)閉流
 with open('./novel/threekingdom.txt', 'r', encoding='utf-8') as f:
     data = f.read()
     print(data)

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

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 f:
    f.write(text)

中文分詞 jieba

PyCharm IDE中,可以直接引入各種工具包。jieba中文分詞工具包安裝非常方便。

1、打開Pycharm,點(diǎn)擊左上角 >>File >>Settings。

2、在settings界面中點(diǎn)擊Project :(項(xiàng)目名稱) >>Project interpreter ?;蛘咴谧笊辖撬阉骺蚶镙斎搿皃roject interpreter”搜索定位。

3、>>點(diǎn)擊右綠色“+”號(hào),添加Package。

4、在可用包界面中,輸入"jieba"搜索,找到j(luò)ieba,點(diǎn)擊下方“Install …”安裝。

5、驗(yàn)證是否安裝成功。再次打開Project interpreter( File >>Settings>>Project :(項(xiàng)目名稱) >> Project interpreter),看到列表中已有Package“jieba”。表明安裝成功。

  • 安裝jieba分詞庫(kù)
  • 指定國(guó)內(nèi)鏡像安裝
  • 1.在用戶目錄下新建pip文件夾
  • 2.新建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é)"
# 精確模式  精確分詞
seg_list = jieba.lcut(seg)
print(seg_list)
# 全模式  找出所有可能的分詞結(jié)果    冗余性大
seg_list1 = jieba.lcut(seg,cut_all=True)
print(seg_list1)
#  搜索引擎模式
seg_list2 = jieba.lcut_for_search(seg)
print(seg_list2)

#
text = '小明碩士畢業(yè)于中國(guó)科學(xué)院計(jì)算所,后在日本京都大學(xué)深造'
seg_list4 = jieba.lcut(text,cut_all=True)
print(seg_list4)
#  搜索引擎模式  先執(zhí)行精確模式,在對(duì)其中的長(zhǎng)詞進(jìn)行處理
seg_list5 = jieba.lcut_for_search(text)
print(seg_list5)

# nlp

import jieba
# 三國(guó)演義小說分詞
# 讀取三國(guó)演義小說
with open('./novel/threekingdom.txt','r', encoding='utf-8') as f:
    words = f.read()
    print(len(words)) # 字?jǐn)?shù)  55萬(wàn)
    words_list = jieba.lcut(words)
    print(len(words_list)) # 分詞后的詞語(yǔ)數(shù)  35萬(wàn)
    print(words_list)

詞云的展示

  • 安裝
  • pip install wordcloud
  • 本地安裝python庫(kù)
# 導(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')

三國(guó)演義小說詞云繪制

# 三國(guó)演義小說分詞
# 讀取三國(guó)演義小說
mask = imageio.imread('./china.jpg')
with open('./novel/threekingdom.txt','r', encoding='utf-8') as f:
    words = f.read()
    # print(len(words)) # 字?jǐn)?shù)  55萬(wàn)
    words_list = jieba.lcut(words)
    # print(len(words_list)) # 分詞后的詞語(yǔ)數(shù)  35萬(wàn)
    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('三國(guó)詞云.png')

效果圖
image
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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