12.13 BMI data.txt的读取与改写

题目描述:

1 Please download the "BMI data.txt" from the Superstar(Chaoxing) platform, read the file, and create a new file "my BMI data.txt" on your computer.

(1) The content of "my BMI.txt" is like the attached picture.

(2) The Categories of BMI is calculated by a function Obesity_judge(BMI). The classify is defined as follows:

BMI Categories:
Underweight = <18.5
Normal weight = 18.5–24.9
Overweight = 25–29.9
Obesity = BMI of 30 or greater

12.13 BMI data.txt的读取与改写_第1张图片

def judge_BMI():
    if BMI <= 18.5:
        return 'Underweight'
    elif 18.5 < BMI <= 25:
        return 'Normal weight'
    elif 25 < BMI <= 29.9:
        return 'Overweight'
    else:
        return 'Obesity'
def judge_sex(m):
    if m == '0':
        return 'Female'
    else:
        return 'Male'
f = open('BMI data.txt','r')
table = []
i = 0
for line in f:
    i = i + 1
    if i == 1:
        continue
    else:
        line = line.split()
        line[1] = judge_sex(line[1])
        SBP_DBP = line[4].split('/')
        SBP = SBP_DBP[0]
        DBP = SBP_DBP[1]
        line.pop(4)
        line.append(SBP)
        line.append(DBP)
        for x in range(2,4):
            try:
                line[x] = float(line[x])
                BMI = line[3] / ((line[2] / 100) ** 2)
                line.append('%.1f' % BMI)
                line.append(judge_BMI())
            except:
                line[x] = line[x]
        table.append(line)
table.insert(0, ['NO.', 'Sex', 'height', 'weight', 'SBP', 'DBP', 'BMI', 'Categories'])
f.close()
f1 = open('my BMI data.txt','w')
for line1 in table:
    for element in line1:
        if element != line1[-1]:
            f1.write(str(element)+'\t')
        else:
            f1.write(str(element)+'\n')
f1.close()

运行结果如图: 

12.13 BMI data.txt的读取与改写_第2张图片

12.13 BMI data.txt的读取与改写_第3张图片

①此处致谢:(参照了红鸽、班里一个大佬的代码)

②第一行不会对齐

你可能感兴趣的:(python)