以下将根据表1中Python程序开发职业技能等级要求(初级)的不同工作领域和任务,分别给出练习代码或操作步骤。
Python基础编程
- 开发环境搭建
- 操作步骤:以Windows系统为例,首先从Python官方网站(https://www.python.org/downloads/ )下载Python安装包,下载完成后运行安装包,记得勾选“Add Python to PATH”选项,以便在命令行中可以直接使用Python命令。安装完成后,打开PyCharm(如果未安装,可从JetBrains官网下载安装),打开PyCharm后,选择“Create New Project”,在弹出的窗口中选择项目保存路径,然后点击“Create”创建项目。在项目的“src”目录(或默认的代码目录)下新建Python文件,例如“test.py”,在文件中输入代码“print(‘Hello, World!’)”,点击右上角的绿色三角形按钮运行代码。
- Python基础应用
- 练习代码
# 标识符命名规范测试
valid_identifier = 123 # 不规范,标识符不能以数字开头
# 修正为
valid_identifier = "abc"
# 数据类型及基础语法
num = 10 # 整数类型
float_num = 3.14 # 浮点数类型
string = "Hello, Python" # 字符串类型
print(type(num))
print(type(float_num))
print(type(string))
# 分支语句
age = 18
if age >= 18:
print("你已成年")
else:
print("你未成年")
# 循环语句
for i in range(5):
print(i)
# 数据结构操作
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # 访问列表元素
my_list.append(6) # 添加元素
print(my_list)
# 函数定义和调用
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result)
- 文件操作
- 练习代码
# open函数操作及文件读写追加
# 写入文件
with open('test.txt', 'w') as f:
f.write("这是写入的内容\n")
# 读取文件
with open('test.txt', 'r') as f:
content = f.read()
print(content)
# 追加文件
with open('test.txt', 'a') as f:
f.write("这是追加的内容\n")
# os模块操作
import os
# 获取当前目录
current_dir = os.getcwd()
print(current_dir)
# 创建新目录
new_dir = 'new_folder'
if not os.path.exists(new_dir):
os.mkdir(new_dir)
Python高阶编程
- 模块、包和异常处理
- 练习代码
# 异常处理
try:
num = 10 / 0
except ZeroDivisionError:
print("除数不能为0")
# 包和模块操作
# 创建一个包,在项目目录下新建一个文件夹,例如“mypackage”,在文件夹内新建一个“__init__.py”文件(内容可以为空),再新建一个模块文件“mymodule.py”
# 在mymodule.py中写入如下代码
def my_function():
print("这是mymodule中的函数")
# 在主程序中导入并使用
from mypackage.mymodule import my_function
my_function()
# 第三方库安装(以requests库为例,在线安装)
# 在命令行中输入:pip install requests
- Python面向对象
- 练习代码
# 类的定义与实例化
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name}在叫:汪汪汪!")
my_dog = Dog("小黑", 3)
my_dog.bark()
# 类的继承
class Puppy(Dog):
def __init__(self, name, age):
super().__init__(name, age)
def play(self):
print(f"{self.name}在玩耍")
my_puppy = Puppy("小白", 1)
my_puppy.bark()
my_puppy.play()
# 封装
class BankAccount:
def __init__(self, balance=0):
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
print(f"存入{amount}元,当前余额为{self.__balance}元")
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance -= amount
print(f"取出{amount}元,当前余额为{self.__balance}元")
else:
print("余额不足")
account = BankAccount(1000)
account.deposit(500)
account.withdraw(800)
# 多态
class Shape:
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
import math
return math.pi * self.radius ** 2
shapes = [Rectangle(5, 3), Circle(4)]
for shape in shapes:
print(f"面积为:{shape.area()}")
- 正则表达式
- 练习代码
import re
text = "我的电话号码是13800138000,邮箱是example@example.com"
# 匹配电话号码
phone_pattern = r'1[3-9]\d{9}'
phone_match = re.search(phone_pattern, text)
if phone_match:
print(f"匹配到电话号码:{phone_match.group()}")
# 匹配邮箱
email_pattern = r'\w+@\w+\.\w+'
email_match = re.search(email_pattern, text)
if email_match:
print(f"匹配到邮箱:{email_match.group()}")
# 贪婪和非贪婪规则
text2 = "<div>内容1</div><div>内容2</div>"
greedy_pattern = r'<div>.*</div>'
non_greedy_pattern = r'<div>.*?</div>'
greedy_match = re.findall(greedy_pattern, text2)
non_greedy_match = re.findall(non_greedy_pattern, text2)
print(f"贪婪匹配结果:{greedy_match}")
print(f"非贪婪匹配结果:{non_greedy_match}")
静态网页开发
- HTML5静态网页开发
- 练习代码(创建一个简单的HTML文件,例如“index.html”)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>我的静态网页</title>
</head>
<body>
<h1>欢迎来到我的网页</h1>
<p>这是一个段落。</p>
<img src="example.jpg" alt="示例图片">
<ul>
<li>列表项1</li>
<li>列表项2</li>
</ul>
<table>
<tr>
<th>表头1</th>
<th>表头2</th>
</tr>
<tr>
<td>单元格1</td>
<td>单元格2</td>
</tr>
</table>
<form>
<input type="text" placeholder="请输入内容">
<input type="submit" value="提交">
</form>
<a href="https://www.baidu.com">跳转到百度</a>
</body>
</html>
- CSS3美化网页
- 练习代码(创建一个CSS文件,例如“styles.css”,并在HTML文件中引入)
/* 选择器获取网页元素 */
h1 {
color: red;
}
p {
font-size: 16px;
}
/* 字体样式、文本样式、颜色、背景等 */
body {
background-color: lightblue;
font-family: Arial, sans-serif;
}
/* 盒模型、浮动、定位 */
img {
float: left;
margin-right: 10px;
}
table {
border-collapse: collapse;
}
td, th {
border: 1px solid black;
padding: 5px;
}
在“index.html”文件的<head>标签内添加<link rel="stylesheet" href="styles.css">引入CSS样式。
3. CSS3动画和可视化操作
- 练习代码(继续在“styles.css”中添加动画相关代码)
/* CSS3 2D变形操作 */
div {
width: 100px;
height: 100px;
background-color: green;
transition: transform 1s;
}
div:hover {
transform: rotate(45deg);
}
/* CSS3帧动画 */
@keyframes myAnimation {
from {
background-color: blue;
}
to {
background-color: yellow;
}
}
.animated-div {
width: 100px;
height: 100px;
background-color: blue;
animation: myAnimation 3s infinite;
}
在“index.html”文件的<body>标签内添加<div class="animated-div"></div>来测试帧动画效果。
- Echarts数据可视化操作:首先需要在HTML文件中引入Echarts库,可以通过CDN引入,在“index.html”的<head>标签内添加<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>,然后在<body>标签内添加一个用于显示图表的DOM元素和一段JavaScript代码来生成图表,示例如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Echarts示例</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
</head>
<body>
<div id="main" style="width: 600px;height:400px;"></div>
<script>
var myChart = echarts.init(document.getElementById('main'));
var option = {
title: {
text: '示例柱状图'
},
xAxis: {
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20, 30]
}]
};
myChart.setOption(option);
</script>
</body>
</html>
静态网络爬虫
- 页面结构分析和爬虫请求库
- 练习代码
import requests
from bs4 import BeautifulSoup
# 发送请求获取页面内容
url = "https://www.example.com" # 替换为实际网址
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.prettify())
else:
print(f"请求失败,状态码:{response.status_code}")
- 数据解析
- 练习代码(继续使用上面的代码获取的
soup对象)
- 练习代码(继续使用上面的代码获取的
# 使用Xpath语法规则分析页面结构(需要安装lxml库,pip install lxml)
from lxml import etree
html = etree.HTML(response.text)
title = html.xpath('//title/text()')
print(title)
# 使用BeautifulSoup4语法规则分析页面结构
title_soup = soup.find('title')
if title_soup:
print(title_soup.text)
- 数据存储与可视化呈现
- 练习代码
import json
import csv
# 假设爬取的数据是一个列表
data = [{"name": "张三", "age": 20}, {"name": "李四", "age": 22}]
# 存储为txt文件
with open('data.txt', 'w') as f:
for item in data:
f.write(str(item) + '\n')
# 存储为json文件
with open('data.json', 'w') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
# 存储为csv文件
with open('data.csv', 'w', newline='') as csvfile:
fieldnames = ['name', 'age']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for item in data:
writer.writerow(item)
# 解析JSON数据
with open('data.json', 'r') as f:
loaded_data = json.load(f)
print(loaded_data)
上述代码和操作步骤涵盖了Python程序开发初级技能要求的主要内容,通过实际练习可以更好地掌握这些技能。在实际运行代码时,请根据具体情况调整代码中的网址、文件路径等参数。
1277

被折叠的 条评论
为什么被折叠?



