Python 导入一个文本 识别文本内的数 然后做出成绩五级比较 输出每个的数量
时间: 2024-03-13 09:46:21 浏览: 19
可以的,您可以按照以下步骤实现:
1. 打开文本文件并读取文件内容
```
with open('filename.txt', 'r') as f:
content = f.read()
```
2. 使用正则表达式提取文本中的数值
```
import re
numbers = re.findall(r'\d+', content)
```
3. 将提取出的数值转换为整数并根据分数划分等级
```
scores = []
for num in numbers:
score = int(num)
if score >= 90:
scores.append('A')
elif score >= 80:
scores.append('B')
elif score >= 70:
scores.append('C')
elif score >= 60:
scores.append('D')
else:
scores.append('E')
```
4. 统计每个等级的数量并输出
```
from collections import Counter
score_count = Counter(scores)
for score, count in score_count.items():
print(f"{score}: {count}")
```
完整代码如下:
```
import re
from collections import Counter
with open('filename.txt', 'r') as f:
content = f.read()
numbers = re.findall(r'\d+', content)
scores = []
for num in numbers:
score = int(num)
if score >= 90:
scores.append('A')
elif score >= 80:
scores.append('B')
elif score >= 70:
scores.append('C')
elif score >= 60:
scores.append('D')
else:
scores.append('E')
score_count = Counter(scores)
for score, count in score_count.items():
print(f"{score}: {count}")
```