0%

这段代码为大一上半学期选修课程Python数据基础与挖掘

如何使用 if 和 else 命令

1
2
3
4
5
6
Name = input("请输入用户名")
Password = input("请输入密码")
if Name == ('admin') and Password == ('123'):
print("登陆成功")
else:
print("登陆失败,账户or密码错误")

使用 for (sth) in range 进行循环命令后 使用 break 停止命令

1
2
3
4
5
6
7
8
9
10
for i in range(3):
Name = input("请输入用户名")
Password = input("请输入密码")
YanZheng = input("请输入验证码")
if Name == ('admin') and Password == ('123') and YanZheng == ("321"):
print("登陆成功")
print("您的余额剩余100万元")
break
else:
print("登陆失败,账户or密码错误")

字符串中的储存方式 —— 下标编号

1
2
name = "abcdef"
print(name[0],name[1])

什么叫切片

1
range[起始:结束:步长]

使用切片加下标编号

1
2
3
4
5
name = "abcdef"
print(name[:1:2],name[::-2])

string ="Life is short,we need python!"
print(string[8:13:1])

字符串内建函数 —— index函数:检测字符串是否包括子字符串

1
2
3
# 具体参数如下:str —— 指定检索字符串、beg —— 开始检索而且默认为零、结束引索而且默认为字符串的长度
# 使用方法跟 find() 一样但是如果str不在string中会出现异常
str.index(str,start = 0,end = len(string))

字符串内建函数 —— replace函数:将旧字符串替换为新字符串

1
2
3
4
5
6
7
# 具体参数如下:old —— 将被替换的字符串、new —— 新字符串且用于替换old字符串、max —— 可选字符串且替换不超过max次
str.replace(old,new[,max])
web = "https://yyxy.sisu.edu.cn/"
dep = ["be","dyx","zwx","media","sibm","sis"]
for a in dep:
url = web.replace("yyxy",a)
print(url)

字符串内建函数 —— split函数:通过指定分隔符对字符串进行切片

1
2
3
4
5
6
7
8
# 具体参数如下:str —— 分隔符而且默认为所有空字符、num —— 分割次
str.split(str = "",num = string.count(str))

string ="Life is short,we need python"
print(string.split("s")[-1])

string ="Life is short,we need python"
print(string.split("h")[1].split("w")[0])

字符串内建函数 —— capitalize与title函数

1
2
3
4
# capitalize:第一个字符大写而且其他字符小写
str.capitalize()
# title:所有单词首字母大写而且其余字母小写
str.title()

字符串内建函数 —— startswith函数:检查字符串是否以制定子串开头

1
2
#  具体参数如下:strbeg —— 可选参数用于设置字符串检查的起始值、strend —— 可选参数用于设置字符串检查的结束位置
str.startswith(str,beg = 0,end = len(string))

字符串内建函数 —— endswith函数:检查字符串是否以制定子串结尾

1
2
# 具体参数如下:suffix —— 该参数可以是一个字符串或者是一个元素、start —— 字符串中的开始位置、end —— 字符串中的结束位置
str.endswith(suffix[,start[,end]])

字符串内建函数 —— upper函数:将小写字母转为大写字母

1
2
3
4
str.upper()
mystr = "I love my lover RongHua"
NewMystr = mystr.upper
print(NewMystr)

字符串内建函数 —— ljust函数:左对齐而且使用空格填充至指定长度的新字符串

1
2
# 具体参数如下:width —— 指定字符串长度、fillchar —— 填充字符而且默认为空格
str.ljust(width[,fillchar])

字符串内建函数 —— strip函数:截掉字符串左右边的空格或指定字符

1
2
3
4
5
# 具体参数如下:chars —— 移除字符串头尾指定的字符
str.strip([chars])

string ="Life is short,we need python!"
print(string.strip("Life i"))

条件语句if-elif-else的使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if condition1:
# 如果条件 1 成立,则执行此处的代码块
elif condition2:
# 如果条件 2 成立,则执行此处的代码块
else:
# 如果所有条件都不成立,则执行此处的代码块

mouth = int(input("请输入你的出生月份: "))
day = int(input("请输入你的出生日期: "))
if mouth == 3 and 21 <= day <= 31 or mouth == 4 and 1<= day <=19:
print("你的星座是白羊座")
elif mouth == 4 and 20 <= day <= 30 or mouth == 5 and 1<= day <=20:
print("你的星座是金牛座")
else:
print("你是其他星座")

字符串中使用“ ”或\t转义字符 空一格

1
2
3
4
string1 = "Hello"
string2 = "World"
print( string1," ",string2 )
print(string1,"\t",string2)

列表aList元素访问与计数

1
2
3
4
5
score = [99,88,92,100,66,85,57,79,90,61]
score[0:5:]

score = [99,88,92,100,66,85,57,79,90,61]
score[2]

列表aList元素的增加指令—append、extend、insert、*

1
2
3
score = [99,88,92,100,66,85,57,79,90,61]
score.insert(2,6)
score[::1]

列表aList元素的删减指令—pop()、remove()

1
2
3
score = [99,88,92,100,66,85,57,79,90,61]
score.pop(1)
score

在列表外/中去使用循环语句去除指定元素

1
2
3
4
5
6
7
8
9
a = [1,2,1,2,1,2]
for i in a:
if i = 1:
a.remove()
print(a)

a = [1,2,1,2,1,2]
a = [i for i in a if i !=1]
print(a)

在列表中使用count()指令查询指定元素次数

1
2
3
4
score = [99,88,92,100,66,85,57,79,90,61]
num = score
count = num.count(90)
print(count)

在列表中使用len()指令查询总元素数量

1
2
3
score = [99,88,92,100,66,85,57,79,90,61]
num = len(score)
print(num)

在列表中使用sort()函数,对函数从小到大排序并输出

1
2
3
score = [99,88,92,100,66,85,57,79,90,61]
score.sort()
print(score)

在列表中使用reverse()函数,颠倒函数顺序

1
2
3
score = [99,88,92,100,66,85,57,79,90,61]
score.reverse()
print(score)

元组的创建与删除 —— 使用tuple函数和del删除

1
2
3
4
5
6
7
8
9
aList = [-1,-4,6,7.5,-2.3,9,-11]
tuple(aList)
print (tuple(aList)[1])

a = [99,88,92,100,66,85,57,79,90,61]
b = tuple(a)
print(b)
del b
print b

序列解包 —— 对于列表和字典同样有效

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 同时对多个变量进行赋值
v_tuple = (False,3.5,'exp')
(x,y,z) = v_tuple
print(x)

# 列表和字典的解包
a = [1,2,3]
b,c,d = a
print(a)
s = {'a':1,'b':2,'c':3}
b,c,d = s.items()
print(b,c,d)

aList = [1,2,3]
bList = [4,5,6]
cList = [7,8,9]
dList = zip(aList,bList,cList)
for index,value in enumerate(dList):
print(index,':',value)

将元组转换成列表的指令 —— list指令

1
2
3
a = ('茸华似雪',520,'唯世恋茸',521)
b = list(a)
print(a)

将元组转换成列表后增添/减少元素

1
2
3
4
a = ('茸华似雪',520,'唯世恋茸',521)
b = list(a)
b[0] = '茸华是小丑'
print(b)

字典创建与删除 —— 创造字典

1
2
3
a_dict = {'name':'茸华似雪','age':18}
x = {} #空字典
print(a_dict,x)

字典创建与删除 —— 相关dict使用

1
2
3
4
5
6
7
8
d = dict(name = '茸华',age = 18)
x = dict() # 空字典
print(d,x)

keys = ['a','b','c']
values = [1,2,3]
dictionary = dict(zip(keys,values))
print(dictionary)

字典创建与删除 —— del使用

1
2
3
add=dict = dict.fromkeys(['name','age','gender'])
print(add)
del add

字典创建与删除 —— get、items的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
a_dict = {'name':'茸华似雪','age':18}
print(a_dict.get('na'))
print(a_dict.get('name'))

a = {'name':'茸华似雪','age':18}
for item in a.items():
print(item)

keys = ['a','b','c']
values = [1,2,3]
dictionary = dict(zip(keys,values))
a = {'name':'茸华似雪','age':18,'gender':'male'}
for keys,values in a.items():
print(keys,values)

字典创建与删除 —— del、clear()、pop()、popitem的使用

1
2
3
4
5
6
7
8
a = {'name':'茸华似雪','age':18}
del a['a']
a = {'name':'茸华似雪','age':18}
a.clear()
a = {'name':'茸华似雪','age':18,'b':5}
a.pop('b')
a = {'name':'茸华似雪','age':18,'b':5}
a.popitem()

Python数据类型

1
2
3
4
5
6
7
8
9
# 整数 int
# 小数 float
# 字符串 string
# 布尔函数 bool
# 列表 list
# 字典 dictionary
# 元组 tuple
# 集合 set
# 函数 def

函数代入数值

1
2
3
4
def add2num(a,b):
c = a + b
print(c)
add2num(11,22)

最常用的有参数有返回值的函数

1
2
3
4
5
6
7
8
9
def Anum(num):
result = 0
i = 1
while i <= num:
result = result + i
i += 1
return result
result = Anum(100)
print('1~100的累积和为:',result)

使用结巴分词库

1
2
3
import jieba
text = '我喜欢茸华似雪'
print(text)

结巴分词的精确模式

1
2
words = jieba.cut(text,cut_all = False)
print('精确模式:','/'.join(words))

结巴分词的全模式

1
2
words = jieba.cut(text,cut_all = True)
print('全模式:','/'.join(words))

结巴分词的搜索模式

1
2
words = jieba.cut_for_search(text)
print('搜索模式:','/'.join(words))

结巴分词的读取自带文件

1
2
3
with open(r'E:/管理学/debug.log',encoding = 'ansi') as f:
text = f.read()
text[0:20] ### 查看前前二十个字母

结巴分词的自定义词典

1
2
3
4
5
import jieba
text = '南京市长江大桥'
jieba.add_word('南京市长')
words = jieba.cut(text)
print('分词后:','/'.join(words))

结巴分词的词性标注

1
2
3
4
5
6
7
8
import jieba.posseg as pseg
text = '我喜欢茸华似雪'
words = pseg.cut(text)
print(type(words))
words = list(words)
print(words)
for word,flag in words:
print(word,flag)

结巴分词的命名实体识别

1
2
3
4
import jieba.analyse
text = '我喜欢茸华似雪'
keywords = jieba.analyse.extract_tags(text,topK=6)
print(keywords)

结巴分词的情感分析

1
2
3
4
5
6
7
8
import jieba.analyse
from snownlp import SnowNLP
text ="我很喜欢这部电影,它让我感到非常感动。"
keywords = jieba. analyse. extract_tags(text,topK=5)
s= SnowNLP(text)
sentiment = s.sentiments
print("关键词:", keywords)
print("情感分析:", sentiment)

结巴分词的提取成语

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import jieba
import jieba.posseg as pseg
### 加载自定义的词典——jieba.load_userdict("idiom_dict.txt")
text = "他说了一句顺口溜:“十年树木,百年树人”,意思是培养人才要从长远考虑。"
words = pseg. cut (text) ### 存储成语及其频次的字典
idioms= {}
for word, flag in words:
### 如果词性标签是i,说明是成语
if flag== "i" :
### 如果成语已经在字典中,则将其频次加 1
if word in idioms:
idioms[word] += 1
### 如果成语不在字典中,则将其加入字典,并将频次初始化为 1
else:
idioms[word] = 1
for idiom,count in idioms.items():
print(idiom,count)

结巴分词的提取成语和介词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import jieba
text = "他在考场上表现得很出色,不过他还有很多不足之处,需要继续努力。"
### 定义用于存储成语和代词的列表
idioms = []
pronouns = []
### 定义成语和代词的集合
idioms_set ={'半途而废','不可思议','不胫而走', '不言而喻','大公无私', '大言不pronouns_set = ('', '','','', '','我们','你们', '他们','她们','它们')
### 对文本进行分词
words = jieba.cut(text)
### 遍历分词后的结果,提取成语和代词
for word in words :
if len(word) == 4 and word in idioms_set :
### 如果是成语,则加入到成语列表中
idioms. append(word)
elif word in pronouns_set:
### 如果是代词,则加入到代词列表中
pronouns. append (word)
### 输出提取结果
print('成语:',idioms)
print('代词:',pronouns)

课堂上词云图作业

from wordcloud import WordCloud                       	#导入
import jieba
import jieba.analyse
import collections
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
with open("C:/Users/69099/Desktop/二十大报告1.txt","r",encoding="utf-8") as file:		#打开文件
    txt = file.read()									#读取文件
    seg_list = jieba.analyse.extract_tags(txt)
    wc_mask = np.array(Image.open("C:/Users/69099/Desktop/f94efe25cfc14c46934a05f046d05e33.png"))
    wc = WordCloud(font_path="C:\Windows\Fonts\simkai.TTF",	#设置属性
                          collocations=False,
                          background_color="white",
                          width=1000,
                          height=800,
                          max_font_size=100,
                          contour_color = 'Blue',
                          mask = wc_mask, #设置背景图
                          contour_width = 2,   #词云边框大小
                          max_words=100).generate(txt)
    wc.generate_from_frequencies(word_counts)

image_colors = wordcloud.ImageColorGenerator(wc_mask)

plt.figure(figsize = [10,10])
plt.imshow(wc)
plt.axis("off")
plt.show()

期末

词性标注

1
2
3
4
5
import jieba.posseg as pseg
text = '我杀掉了你的全家'
words = pseg.cut(text)
words = list(words)
print(words)

增加自定义词典

1
2
3
4
5
6
7
8
9
10
import jieba
text = '我是茸华似雪'
words = jieba.lcut(text,cut_all=True)
print('分词前:',words)
## ===================================
import jieba
jieba.add_word('茸华')
text = '我是茸华似雪'
words = jieba.lcut(text,cut_all=True)
print('分词后:',words)

词频前10排序

1
2
3
4
5
6
7
8
9
10
import jieba
with open("C:/Users/69099/Desktop/11.txt","r",encoding="utf-8") as file: # 打开文件
txt = file.read() # 读取文件
text = jieba.lcut(txt) # 分词
counts = {} # 统计词频
for i in text:
if len(i) > 1: # 统计长度为1的词
counts[i] = counts.get(i,0) + 1
Text = sorted(counts.items(),key = lambda x:x[1],reverse = True) # 词频排序
print(Text[:10])

柱状图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import matplotlib.pyplot as plt                                                 # 导入matplotlib库
import numpy as np # 导入numpy库
plt.figure(figsize=(8, 6), dpi=100) # 创建一个点数为 8 x 6 的窗口, 并设置分辨率为 80像素/每英寸
plt.subplot(1, 1, 1) # 再创建一个规格为 1 x 1 的子图
N = 6 # 柱子总数
values = (250, 320, 340, 200, 410, 500) # 包含每个柱子对应值的序列
index = np.arange(N) # 包含每个柱子下标的序列
width = 0.65 # 柱子的宽度
p2 = plt.bar(index, values, width, label="rainfall", color="#87CEFA") # 绘制柱状图, 每根柱子的颜色为紫罗兰色
plt.xlabel('Months') # 设置横轴标签
plt.ylabel('rainfall (mm)') # 设置纵轴标签
plt.title('Monthly average rainfall') # 添加标题
plt.xticks(index, ('Jan', 'Fub', 'Mar', 'Apr', 'May', 'Jun')) # 添加纵横轴的刻度
plt.yticks(np.arange(0, 810, 100))
plt.legend(loc="upper right") # 添加图例
plt.show()

词云图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from wordcloud import WordCloud                                                 # 导入词云图库
import jieba # 导入jieba分词库
import jieba.analyse # 导入jieba的核心词提取analyse模块
import numpy as np # 导入NumPy函数库
from PIL import Image # 导入PIL库中Image
import matplotlib.pyplot as plt # 导入matplotlib.pyplot库
with open("C:/Users/69099/Desktop/11.txt","r",encoding="utf-8") as file: # 打开文件
txt = file.read() # 读取文件
seg_list = jieba.analyse.extract_tags(txt) # 关键词的提取
wc_mask = np.array(Image.open("C:/Users/69099/Desktop/QQ图片20231221152454.png"))
wc = WordCloud(font_path="C:\Windows\Fonts\simkai.TTF", # 设置属性
collocations=False,
background_color="white",
width=1000,
height=800,
max_font_size=100,
contour_color = 'Blue',
mask = wc_mask, # 设置背景图
contour_width = 2, # 词云边框大小
max_words=100).generate(txt)
plt.figure(figsize = [10,10])
plt.imshow(wc)
plt.axis("off")
plt.show()

本代码是学习演示过程

print语句使用——用于输出目标

1
print("Hello World")

赋予变量值

1
2
money=50
print("钱包里面有: ", money)

变量的加减变化

1
2
money=money-10
print("购买了冰淇淋花费了10元,还剩余: ", money,"元")

type()语句的使用——用于查看变量存储数据类型

1
2
3
4
string_type=type("卧室嫩叠")
int_type=type(233)
float_type=type(1.666)
print(string_type,int_type,float_type)

str(x)语句——用于将数字类型转换为字符串

1
2
3
num_str=str(11)
float_str=str(11.11)
print(type(num_str),num_str,type(float_str),float_str)

int(x)和float(x)语句——用于将字符串转换成数字而——浮点转整数与整数转浮点数

1
2
3
num_int=int("11.1")
num_float=float("11")
print(type(num_int),num_int,type(num_float),num_float)

错误示例——将字符串转换为数字的前提是字符串为数字

1
2
3
num1=int("卧室嫩叠")
num2=float("卧室嫩叠")
print(type(num1),num1,type(num2),num2)

Python规则一: 内容限定——限定只能使用:中文、英文、数字、下划线,注意:

1
2
3
4
5
##### 错误示例 1_name="张三"
##### 错误示例 name_!="张三"
name_="张三"
_name="张三"
name_1="张三"

python规则二:大小写敏感

1
2
3
4
Ronghua="My Lover"
ronghua=520
print(ronghua)
print(Ronghua)

python规则三:不可使用关键词

1
2
3
4
错误的示例 使用了关键字:class=1
错误的示例 使用了关键字:def=1
Class=1
Def=1

字符串在Python中有多种定义形式:

1.单引号定义法:

1
2
name = '茸华似雪'
print(type(name))

2.双引号定义法:

1
2
name = "茸华似雪"
print(type(name))

3.三引号定义法:

1
2
3
4
5
6
name = """茸华似雪"""
print(type(name))
name = """
唯世恋茸
"""
print(type(name))

在字符串内 包含双引号

1
2
name = '"茸华似雪"'
print(type(name))

在字符串内 包含单引号

1
2
name = "'茸华似雪'"
print(name)

使用转义字符/解除引号的效用

1
2
3
name = "\"茸华似雪\""
name_1 = '\'茸华似雪\''
print(name,name_1)

字符串字面量之间的拼接

1
print("茸华似雪"+"唯世恋茸")

字符串字面量和字符串变量的拼接

1
2
name = "茸华似雪"
print("我的名字是:"+ name +",我喜欢唯世恋茸.")

字符串无法通过加法和数字拼接

1
2
错误的示例 tel = 666 
print("茸华似雪的电话是:"+ tel)

字符串格式化一——通过占位的形式完成拼接

1
2
3
name = "茸华似雪"
message = "我的名字是:%s" % (name)
print(message)

字符串格式二——通过占位的形式完成数字和字符串的拼接

1
2
3
4
class_num = 5
avg_salary = 3500
message = "四川外国语大学,金融学%s班,毕业平均工资:%s" %(class_num,avg_salary)
print(message)

格式符号$s $d $f的转化

1
2
3
4
5
6
7
8
## $s 将内容转换成字符串并且放入占位位置
## $d 将内容转换成整数并且放入占位位置
## $f 将内容转换成浮点型并且放入占位位置
name = "茸华似雪"
set_up_year = 2018
love_year = 5.2
message = "我是:%s,我诞生于:%d年,我今天喜欢茸华已经:%f年了!" % (name,set_up_year,love_year)
print(message)

字符串格式化 —— 数字精度控制(m:控制宽度 .n控制小数点) —— .n会进行小数的四舍五入

1
2
3
4
5
6
num1 = 520
num2 = 521.13136
print('数字520宽度限制5,输出结果为:%5d' % num1 )
print('数字520宽度限制1,输出结果为:%1d' % num1 )
print('数字520.13135宽度限制10并且小数精度4,输出结果为:%10.4f' % num2 )
print('数字520.13135宽度无限制并且小数精度4,输出结果为:%.4f' % num2 )

字符串格式化 —— 快速格式化写法

1
2
3
4
5
#### f"内容{变量}" 不限类型不控精度(format)
name = "茸华似雪"
born_year = 2018
lover = '茸华'
print(f"我是{name},我出生于:{born_year},我喜欢的人是:{lover}")

字符串格式化 —— 对表示式格式化 —— 表达式:一条具有明确执行结果的代码语句

1
2
3
print("我喜欢你的结果是:%d" % (10 * 52))
print(f"我喜欢你的结果是:{13 * 101 + 1}")
print('我最喜欢的人从以前到现在都是:%s' % ('茸华似雪') )

课程练习题一

1
2
3
4
5
6
7
8
name = '茸华阁有限公司'                  #### 公司名字
stock_price = 521.0 #### 当前股价
stock_code = 1314 #### 股票代码
stock_price_daily_growth_factor = 1.2 #### 股票每日增长系数(浮点数类型)
growth_days = 7 #### 股价增长天数
##### 计算经过gorwth_days天的增长后,股价达到了多少钱
##### 使用字符串格式化进行输出,如果是浮点数,要求小数点精度两位数
print("我们是:%s,股票代码为:%d,当前的股价是:%.1f" % (name,stock_code,stock_price) ,f"每日增长系数为{stock_price_daily_growth_factor},经过{growth_days}天的增长后股价达到了:{stock_price * (stock_price_daily_growth_factor * growth_days)}")

Welcome to RongHuaSiXue.com!

欢迎来到我的个人博客——茸华似雪的茸华坊

Why print Hello World

“Hello, world”程序是指在计算机屏幕上输出“Hello world”这行字符串的计算机程序,“Hello World”的中文意思是“你好,世界。”。这个例程在 Brian Kernighan 和 Dennis M. Ritchie合著的The C Programme Language使用而广泛流行。因为它的简洁,实用,并包含了一个该版本的C程序首次在1974年 Brian Kernighan 所撰写的 Programming in C: A Tutorial 出现。

When printf(“hello, world\n”)

实际上将“Hello”和“World”一起使用的程序最早出现于1972年,在贝尔实验室成员Brian Kernighan撰写的内部技术文件《Introduction to the Language B》之中。最初的”hello, world”打印内容有个标准,即全小写,有逗号,逗号后空一格,且无感叹号。不过,完全遵循传统标准形式的反而很少出现。