函數(shù)
細節(jié)
- import 文件名 可以導(dǎo)入自己的文件調(diào)用其中的模塊,如函數(shù)
import caculate
res = caculate.caculateNum(100)
print(res)
輸出

image.png
- 列表推導(dǎo)式實現(xiàn)一行輸出
def caculateNum(num):
# res = 0
# for i in range(1, num+1):
# res += i
# return res
return sum([i for i in range(1, num+1)])
- 必須參數(shù)和關(guān)鍵字參數(shù)
#必須參數(shù)和關(guān)鍵字參數(shù)
def f(name, age):
print('I am %s , I am %d'%(name, age))
#關(guān)鍵字參數(shù),此時允許函數(shù)調(diào)用和聲明時順序不一樣
f(age=18, name='eric')
- 默認參數(shù)
#默認參數(shù) 缺省參數(shù)沒有傳入,默認值會生效
def f(name, age, sex = 'male'):
print('I am %s , I am %d'%(name, age))
print('Sex%s'%sex)
f(name='lisi', age=19)
f('張三', 88, 'female')
#是否顯示指定參數(shù):方便自己閱讀為目的
輸出

image.png
- 匿名函數(shù)
和條件判斷式一起使用更加
# 匿名函數(shù)
# 語法 :
# lambda 參數(shù): 表達式
#冒號前面是參數(shù),可以有多個,冒號后面時表達式
#只能有一個,不寫return 返回值是表達式的結(jié)果
#減少代碼量,‘優(yōu)雅
def rect(x, y):
return x * y
area = rect(3, 5)
print(area)
#使用lambda表達式
res = lambda x, y: x*y
print(res(4, 5))
store = []
s = "dangdangziying" if len(store) == 0 else store[0]
print(s)
def cal(x, y):
if x>y:
return x*y
else:
return x/y
calc = lambda x, y: x*y if x > y else x/y
print(calc(5, 4))
calc = lambda x, y: x*y if x > y else x/y
print(calc(2, 4))
輸出

image.png
在列表排序中的使用
#列表排序中使用
stus = [
{'name': 'zhangsan', 'age': 33},
{'name': 'lisi', 'age': 12},
{'name': 'wangwu', 'age': 53},
{'name': 'zhaoliu', 'age': 18},
{'name': 'tianqi', 'age': 77}
]
print(stus)
#key值按照哪個元素為依據(jù)排序
res = sorted(stus, key=lambda x: x['age'], reverse=True)
print('排序后', res)
res = sorted(stus, key=lambda x: x['name'], reverse=True)
print('排序后', res)
輸出

image.png
- 綜合案例
三國中人物出現(xiàn)的次數(shù)
用wordcloud生成詞云圖片
# 案例三國小說人物出場頻率統(tǒng)計
import jieba
from collections import Counter
from wordcloud import WordCloud
def parse():
# 定義無關(guān)詞集合
excludes = {"將軍", "卻說", "丞相", "二人", "不可", "荊州", "不能", "如此", "商議",
"如何", "主公", "軍士", "軍馬", "左右", "次日", "引兵", "大喜", "天下",
"東吳", "于是", "今日", "不敢", "魏兵", "陛下", "都督", "人馬", "不知",
'玄德曰', '孔明曰', '劉備', '關(guān)公'
}
"""三國小說人物出場頻率統(tǒng)計"""
with open('threekingdom.txt', 'r', encoding='utf-8') as f:
txt = f.read()
# print(txt)
words = jieba.lcut(txt)
print(words)
# 鍵是名字
counts = {}
for word in words:
if len(word) == 1:
continue
else:
# 向字典中增加元素 缺省值為0
counts[word] = counts.get(word, 0)+1
print(counts)
# 統(tǒng)計標準
counts['孔明'] = counts.get('孔明') + counts.get('孔明曰')
counts['玄德'] = counts.get('玄德曰') + counts.get('玄德')
counts['玄德'] = counts.get('玄德') + counts.get('劉備')
counts['關(guān)公'] = counts.get('關(guān)公') + counts.get('云長')
for word in excludes:
del counts[word]
# 統(tǒng)計出現(xiàn)頻次最高的前20個詞
items = list(counts.items())
# print(items)
items.sort(key=lambda x: x[1], reverse=True)
# print('排序后', items)
for i in range(20):
character, count = items[i]
print(character, count)
#方法2
roles = Counter(counts)
role = roles.most_common(10)
print(role)
# 構(gòu)造詞云字符串
li = []
for i in range(10):
character, count = items[i]
for _ in range(count):
li.append(character)
print(li)
cloud_txt = ",".join(li)
wc = WordCloud(
background_color='while',
font_path='msyh.ttc',
# 是否包含兩個詞的搭配,莫熱門true
collocations=False
).generate(cloud_txt)
wc.to_file('三國詞云.png')
parse()
# jieba分詞
txt = '我來到北京清華大學(xué)'
# 將字符串分割成等量中文
seg_list = jieba.lcut(txt)
print(seg_list)
輸出

image.png
這里得包不好導(dǎo),在自己得電腦中
pip install xxxxx
然后file-setting-project-interpreter 然后右上角加號導(dǎo)入包到項目中