Question: Students with academic scores >= 90 points are represented by A, students with scores between 60-89 are represented by B, and students with scores below 60 are represented by C.
Option 1: Use if statement to determine
- Use Python's built-in open() function to open the txt file, use the read() method to read the contents of the file, and use the splitlines() method to split each line.
- Traverse each row, judge the score of each student, divide it into three categories: A, B, and C based on the score, and splice the rating results to the end of each row
- Use the write() method to write the rated content back to the txt file
Advantages: Simple to implement and easy to understand
Disadvantages: The code has poor readability. When the judgment conditions are many and complex, the amount of code will increase and it will be difficult to maintain.
with open('scores.txt', 'r') as f:
lines = f.readlines() # 读取所有行
with open('scores.txt', 'w') as f:
for line in lines:
score = int(line.strip()) # 去除换行符并转为整数
if score >= 90:
level = 'A'
elif score >= 60:
level = 'B'
else:
level = 'C'
f.write('{} {}\n'.format(line.strip(), level)) # 写入原始分数和评级
Option 2: Use list comprehensions and lambda functions
- Use Python's built-in open() function to open the txt file, use the read() method to read the contents of the file, and use the splitlines() method to split each line.
- Traverse each row, use list derivation and lambda function to judge the score of each student, divide it into three categories: A, B, and C according to the score, and splice the rating results to the end of each row
- Use the write() method to write the rated content back to the txt file
Advantages: The code is concise, highly readable, and suitable for some simple data operations.
Disadvantages: When the judgment conditions are complex, readability will decrease and it will be difficult to maintain.
# lambda函数用于将数值转换成对应的等级
get_grade = lambda score: 'A' if score >= 90 else ('B' if score >= 60 else 'C')
with open('scores.txt', 'r') as f:
# 读取每一行并根据空格分割成列表
scores = [line.strip().split() for line in f.readlines()]
# 将每个学生的成绩转换成对应的等级,并将结果追加到列表中
grades = [[*score, get_grade(int(score[-1]))] for score in scores]
with open('grades.txt', 'w') as f:
# 将每个学生的信息写入文件中
for grade in grades:
f.write(' '.join(grade) + '\n')
Option 3: Use the pandas library for data processing
- Read txt files using the read_csv() method of the pandas library
- Use the apply() method to judge the score of each student, divide it into three categories: A, B, and C based on the score, and add the rating results to a new column.
- Use the to_csv() method to write the processed data back to the txt file
Advantages: The pandas library has powerful data processing capabilities, can perform data operations quickly and efficiently, and the code is highly readable.
Disadvantages: For simple data operations, using the pandas library is a bit too complicated, and you need to install the third-party library pandas
import pandas as pd
# 读取txt文件,假设文件中有两列,分别为name和score
df = pd.read_table('data.txt', sep='\s+', header=None, names=['name', 'score'])
# 定义评级函数
def get_grade(score):
if score >= 90:
return 'A'
elif score >= 60:
return 'B'
else:
return 'C'
# 添加评级列
df['grade'] = df['score'].apply(get_grade)
# 根据评级列进行排序
df.sort_values(by=['grade'], ascending=False, inplace=True)
# 将结果写入txt文件
df.to_csv('result.txt', index=False, sep='\t', header=None)