用python写可以获取电脑文件内指定内容并且分类
时间: 2024-03-11 21:43:29 浏览: 18
可以使用Python的文件读写操作和正则表达式来实现获取电脑文件内指定内容并分类的功能。
以下是一个示例代码,假设我们需要从一个包含多个学生信息的文本文件中获取所有学生的姓名和成绩,并根据成绩将学生分为优秀、良好和及格三类,并分别输出到不同的文件中:
```python
import os
import re
# 搜索指定目录下的所有文本文件
directory = '/Users/username/Documents/'
files = [os.path.join(directory, f) for f in os.listdir(directory) if f.endswith('.txt')]
# 匹配姓名和成绩的正则表达式
pattern = r'姓名:(.+?)\s+成绩:(\d+)'
# 遍历所有文件,并根据成绩将学生分为优秀、良好和及格三类
excellent_students = []
good_students = []
pass_students = []
for file in files:
with open(file, 'r') as f:
content = f.read()
matches = re.findall(pattern, content)
for name, score in matches:
score = int(score)
if score >= 90:
excellent_students.append(f'{name} {score}')
elif score >= 80:
good_students.append(f'{name} {score}')
else:
pass_students.append(f'{name} {score}')
# 将每个类别的学生姓名和成绩输出到不同的文件中
excellent_file = open('excellent_students.txt', 'w')
good_file = open('good_students.txt', 'w')
pass_file = open('pass_students.txt', 'w')
for student in excellent_students:
excellent_file.write(f'{student}\n')
for student in good_students:
good_file.write(f'{student}\n')
for student in pass_students:
pass_file.write(f'{student}\n')
excellent_file.close()
good_file.close()
pass_file.close()
```
在这个示例代码中,我们首先使用`os.listdir`函数列出指定目录下的所有文本文件,并使用列表推导式生成文件路径列表。然后,我们遍历所有文件,并使用正则表达式匹配学生的姓名和成绩,并将学生分为优秀、良好和及格三类,并将每个类别的学生姓名和成绩存储在不同的列表中。最后,我们将每个类别的学生姓名和成绩输出到不同的文件中。
这个示例代码只是一个简单的例子,你可以根据自己的需求来修改目录、文件类型、正则表达式和分类逻辑来实现更加复杂的功能。