2016년 6월 29일 수요일

python으로 파일에 있는 단어의 갯수 세기

킹제임스 버전의 영어 성경입니다. 코드는 아래와 같습니다.

# most_common_words.py
import sys
from collections import Counter

if __name__ == "__main__":
    try:
        num_words = int(sys.argv[1])
    except:
        print("usage: most_common_words.py num_words")
        sys.exit(1)

    counter = Counter(word.lower() \
                      for line in sys.stdin
                      for word in line.strip().split()
                      if word)

    for word, count in counter.most_common(num_words):
        sys.stdout.write(str(count))
        sys.stdout.write("\t")
        sys.stdout.write(word)
        sys.stdout.write("\n")


다음과 같이 실행하면됩니다.

C:\work>type the_bible.txt | python most_common_words.py 20


댓글 없음:

댓글 쓰기

참고: 블로그의 회원만 댓글을 작성할 수 있습니다.

제 AI는 스스로 생각하고 학습한다.. 난리난 AI 에이전트 직접 확인해보니 - 영상정리해 봅니다.

  ChatGPT가 나온지 3년이 넘었습니다. ㅎㅎ 처음에는 생성형AI에서 LLM으로 시장이 변화되었습니다. 작년말부터는 에이전트의 시대라고 하고 있습니다. 저도 관련 강의를 하고 일을 하고 있지만 따라가기가 벅찰정도로 매주 새로운 소식들이 올라옵니다...