2016-06-11 6 views
0

특정 주제 태그 (문자열) 다음에 등급 (숫자)을 읽고 쓰고 싶습니다. 그래서 나는 모든 것을 가지고 있습니다. 그러나 그 태그를 찾아서 어떻게 쓰는지를 알아낼 수는 없습니다.문자열 뒤에 파일 쓰기

MAT54324524342211 

그리고 무슨 일이 지금까지 시도 :

그래서, 예를 들어, 유효한 입력이 될 것

save = open("grades.txt", "w") 

def add(x, y): 
    z = x/y * 100 
    return z 

def calc_grade(perc): 
    if perc < 50: 
     return "1" 
    if perc < 60: 
     return "2" 
    if perc < 75: 
     return "3" 
    if perc < 90: 
     return "4" 
    if perc >= 90: 
     return "5" 

def calc_command(): 
    num1 = input("Input your points: ") 
    num2 = input("Input maximum points: ") 
    num3 = add(float(num1), float(num2)) 
    grade = calc_grade(num3) 
    print("This is your result:", str(num3) + "%") 
    print("Your grade:", grade) 
    save.write(grade) 


while True: 
    command = input("Input your command: ") 
    if command == "CALC": 
     calc_command() 
    if command == "EXIT": 
     break 

어떤 아이디어? 죄송합니다. 이것은 내 코드의 이전 버전입니다. 새로운 버전은 내 성적을 인쇄 한 후 save.write (등급)입니다. 프로그램이 완료되지 않았습니다. 최종 아이디어는 내 txt 파일에 주제 태그 묶음을 가져오고 사용자는 어떤 주제가 성적인지 선택합니다.

+0

모를 수가 귀하의 질문을 얻을. 몇 가지 예를 들어 설명해 주시겠습니까 ?? –

+0

귀하의 질문은 다소 모호합니다. 그러나 파일에서 데이터를 읽으려면 "w"모드로 열지 마십시오. [this answer] (http://stackoverflow.com/a/1466036/4014959)에있는 모든 표준 파일 모드에 대한 좋은 요약이 있습니다. –

+0

좋습니다. 예를 들어 텍스트 파일에 다음과 같이 입력 할 수 있습니다. MAT54355와 MAT 뒤에 쓰기를 원합니다. 그게 과목으로 성적을 분류하고 싶거나 더 좋은 방법이 있기 때문입니다. –

답변

0

표준 라이브러리와 함께 제공되는 것을 다시 구현하지 마십시오.

스크립트의 일부 구현이 될 것 json를 사용하여 :

import os 
import json 


def read_grades(filename): 
    if os.path.exists(filename): 
     with open(filename, 'r') as f: 
      try: 
       return json.loads(f.read()) 
      except ValueError as ex: 
       print('could not read', ex) 
    return {} 


def write_grades(filename, grades): 
    with open(filename, 'w') as f: 
     try: 
      f.write(
       json.dumps(grades, indent=2, sort_keys=True) 
      ) 
     except TypeError as ex: 
      print('could not write', ex) 


def question(text, cast=str): 
    try: 
     inp = input(text) 
     return cast(inp) 
    except Exception as ex: 
     print('input error', ex) 
     return question(text, cast=cast) 


def calculator(grades): 
    def add(x, y): 
     assert y != 0, 'please don\'t do that' 
     z = x/y 
     return z * 100 

    def perc(res): 
     for n, p in enumerate([50, 60, 75, 90], start=1): 
      if res < p: 
       return n 
     return 5 

    subject = question('enter subject: ').strip() 
    points = question('your points: ', cast=float) 
    max_points = question('maximum points: ', cast=float) 

    result = add(points, max_points) 
    grade = perc(result) 

    print('> {subject} result: {result:.2f}% grade: {grade}'.format(
     subject=subject.capitalize(), 
     result=result, grade=grade 
    )) 

    grades.setdefault(subject.lower(), list()) 
    grades[subject.lower()].append(grade) 

    return grades 


def show(grades): 
    print('>> grades') 
    for subject in sorted(grades.keys()): 
     print('> {subject}: {grades}'.format(
      subject=subject.capitalize(), 
      grades='; '.join(str(g) for g in grades[subject]) 
     )) 


def main(): 
    filename = 'grades.json' 
    grades = read_grades(filename) 

    while True: 

     grades = calculator(grades) 
     show(grades) 

     if not question('continue? (hit enter to quit) '): 
      break 

    write_grades(filename, grades) 

if __name__ == '__main__': 
    main() 

grades.json 지금 키와 같은 주제와 dictionary 및 값으로 모든 성적의 list 포함

{ 
    "art": [ 
    3 
    ], 
    "math": [ 
    4, 
    5 
    ] 
}