ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [두근두근 파이썬 11장] 실습 10주차
    학교 수업/1-1, 1-2 코딩 기초 (파이썬, C) 2020. 5. 21. 15:56
    반응형

    컴퓨팅적 사고와 문제 해결 5월 19일 실습 과제(두근두근 파이썬 11장 연습문제)

     

     

    연습문제 1

    filename = input("파일 이름을 입력하세오: ") #파일 경로 입력
    infile = open(filename,"r")
    ans = 0
    for line in infile:#여러 줄이 있을 경우 각 줄을 line이라는 변수에 저장함
        words = line.split()
        for word in words:
            ans += len(word) #글자 수를 더함
    print("파일 안에는 총",ans,"개의 글자가 있습니다.")
    

     

    연습문제 2

    filename = input("파일 이름을 입력하세오: ") #파일 경로 입력
    infile = open(filename,"r")
    read_file = infile.readlines()
    
    outfile = open(filename, "w")
    del_word = input("삭제할 문자열을 입력하시오: ")#삭제할 문자열 입력
    
    for line in read_file: #여러 줄이 있으면 한 줄씩 처리함
        l, r = 0, len(del_word)
        new_line = "" #삭제하지 않아도 되는 문자열을 저장함
        while l < len(line): #while문으로 삭제할 단어를 찾아냄
            if line[l:r] == del_word: #만약 삭제할 단어가 있을 경우
                l += len(del_word)
                r += len(del_word)
            else: #삭제할 단어가 아닌 경우
                new_line += line[l]
                l+=1
                r+=1
        print(new_line, file = outfile, end="") #new_line에 저장한 문자열을 outfile에 작성해줌
    
    infile.close()
    outfile.close()
    print("변경된 파일이 저장되었습니다.")
    

     

    연습문제 5

     

    infilename = input("입력 파일 이름: ") #입력 파일 경로 입력
    outfilename = input("출력 파일 이름: ") #작성할 파일 경로 입력
    
    infile = open(infilename,"r")
    outfile = open(outfilename,"w")
    ans = 0 # 숫자를 더해줄 변수를 만들었음
    k = 0 # infile에 있는 숫자가 몇 개나 있는지 확인하는 변수를 만들었음
    
    for line in infile:
        ans += float(line) #메모장에 적힌 숫자를 더해줌
        k += 1 #k에 1을 더해줘서 나중에 평균을 구할 때 사용함
    
    #output 메모장에 합계와 평균을 적어줌
    print("합계="+str(ans), file = outfile)
    print("평균="+str(ans/k), file = outfile)
    
    infile.close()
    outfile.close()
    
    반응형

    댓글

Designed by Tistory.