IT/Python
[Python] 글에 사용된 단어 수 세기
잿호
2023. 9. 9. 12:38
설계
1. 글의 사용된 단어를 카운트하여 딕셔너리에 저장한다.
2. 공백, 줄 바꿈기호, 따옴표 등은 지워준다.
3. python/data 경로에 존재하는 txt문서를 불러온다
코드
file = open('data/문재인대통령.txt', 'r', encoding = 'utf-8')
contents = file.read()
#contents = str(input('내용 : '))
contents = contents.replace('\n',' ')
contents = contents.replace('!','')
contents = contents.replace('.','')
words = contents.split(' ')
word_dict = {}
for word in words:
if word not in word_dict:
word_dict[word] = 0
word_dict[word] += 1
print(word_dict)
실행
01
마무리
대통령연설문 자료는 https://www.pa.go.kr/index.jsp 에서 가져왔다.
1번째 줄을 지우고 2 번째 줄 contents 변수에 input을 넣어주면 뉴스 글 복붙도 가능하다.
반응형