score = open("score.txt", "r+")
lines = score.readlines()
score.close()
def rank(score):
if score > 100:
print("超過100分")
elif score >= 100:
print("A+")
elif score >= 95:
print("A")
elif score >= 90:
print("A-")
elif score >= 85:
print("B+")
elif score >= 80:
print("B")
elif score >= 75:
print("B-")
elif score >= 70:
print("C+")
elif score >= 65:
print("C")
elif score >= 60:
print("C-")
elif score >= 1:
print("F")
else:
print("X")
for line in lines:
print(line)
data = line.split(",")
print(data)
for ranking in data[2:]:
result = (data[0], data[2], rank(score))
print(result)
results.append(result)
print(results)
output = open('D0586499.txt', 'w')
output.writelines(results)
output.close()
請問我要將Score.txt裡面的score單獨分離出來,並且將它用程式碼作成績及等的排列,最後再output到新的文件裡,請問有甚麼辦法可以單獨讀出成績,並且將他轉成整數,作成績排列?
目前遇到的問題是不知如何分離出需要的資料,且沒辦法排列,請求各位大神幫幫忙~~~
要先用 PIL, cv2, numpy training 一個模型辨識圖片....
檔案是 txt 就用 txt 的方式處理
from re import *
from math import *
def rank(score):
obj = ['A+', 'A+', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'F', 'X']
return obj[10] if score == 0 else obj[9] if score < 60 else obj[ceil((100 % score) * 0.2)]
# 更新一下加了 X 原本的判斷會失準
result = ""
with open('score.txt', 'r') as f:
for i, item in enumerate(f):
data = item.split(",")
if i == 0:
result += item
continue
score = data[1]
rankStr = rank(int(score))
result += sub("\n", rankStr + "\n", item)
with open('score.txt', 'w') as wf:
wf.write(result)
補充用 numpy+pandas 的作法
from math import *
import pandas as pd
import numpy as np
obj = ['A+', 'A+', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'F', 'X']
rank = lambda score: obj[10] if score == 0 else obj[9] if score < 60 else obj[ceil((100 % score) * 0.2)]
df = pd.read_csv('score.txt', sep=",")
vRank = np.vectorize(idx)
df['rank'] = vRank(np.array(df["score"].astype(int)))
df.to_csv('score.txt', index=False)
不過感覺寫的很糙
同場加映 dragonH 大推薦的 select
看起來清爽許多
import pandas as pd
import numpy as np
df = pd.read_csv('it20200429.txt', sep=",")
obj = ["A+", "A+", "A-", "B+", "B", "B-", "C+", "C", "C-", "F","X"]
conditions = [
df['score'] == 100,
df['score'] >= 95,
df['score'] >= 90,
df['score'] >= 85,
df['score'] >= 80,
df['score'] >= 75,
df['score'] >= 70,
df['score'] >= 65,
df['score'] >= 60,
df['score'] >= 1,
df['score'] == 0
]
df["rank"] = np.select(conditions, obj)
df.to_csv('score.txt', index=False)
pandas + numpy 就搞定了其實
寫完他應該也看不懂
謝謝大大的熱心回答!!
andy2435喜歡麻煩給個五星好評 雙擊最佳解答666
numpy 有 select
可以用呀XD
code
import pandas as pd
import numpy as np
df = pd.read_csv('datas.csv')
conditions = [
df['score'] > 100,
df['score'] == 100,
df['score'] >= 95,
df['score'] >= 90,
df['score'] >= 85,
df['score'] >= 80,
df['score'] >= 75,
df['score'] >= 70,
df['score'] >= 65,
df['score'] >= 60,
df['score'] >= 1,
df['score'] == 0
]
grades = [
'超過100',
'A+',
'A',
'A-',
'B+',
'B',
'B-',
'C+',
'C',
'C-',
'F',
'X'
]
df['grade'] = np.select(conditions, grades)
result