오늘의 인기 글
최근 글
최근 댓글
Today
Total
05-04 00:00
관리 메뉴

우노

[Python] sys.stdin 본문

Language/Python

[Python] sys.stdin

운호(Noah) 2020. 9. 15. 11:19
  • 파이썬에서 입력 값을 받을 때 보통 input()을 이용한다.

  • 하지만 알고리즘에서 input()을 이용할 때 종종 시간 초과가 발생하기 때문에 sys 모듈의 sys.stdin을 사용한다.

  • 단, 이때는 맨 끝의 개행문자까지 같이 입력받기 때문에 문자열을 저장하고 싶을 경우 .rstrip()을 추가로 해 주는 것이 좋다.

  • 여러 줄을 문자열로 입력 받고 싶을 때

      import sys
    
      lines = sys.stdin.read()
  • 여러 줄을 리스트로 입력 받고 싶을 때

      import sys
    
      lines = sys.stdin.readlines()
  • 간단한 stdin, stdout 예제

      import re
      from collections import Counter
      import sys
    
      # 파일 입력 받기
      document = sys.stdin.read()
    
      # 문자열 전체 소문자로 변환
      document_lower = document.lower()
    
      # 문자열에서 알파벳과 숫자만 가져와 리스트화
      words = re.findall('[a-z0-9]+',document_lower)
    
      # 문서에 나타난 단어 리스트 Count
      word_counts = Counter(words)
    
      # 가장 많이 등장한 단어 1000개 뽑아 표준출력하기
      for word, count in word_counts.most_common(1000):
          sys.stdout.write(word + '\t' + str(count) + '\n')
Comments