Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 업다운게임코드
- 컴퓨터일반
- 파이썬공부
- 안드로이드스튜디오
- bottomnavigation
- 운영체제종류
- 데이터베이스
- 정보처리산업기사
- 정처산기
- 안드로이드
- 자바예제
- 코딩공부
- 코딩
- 파이썬리스트
- 바텀네비게이션
- 운영체제목적
- 파이썬
- 자바
- 엑티비티
- 스누핑
- 정처기
- 파이썬예제
- 정처기운영체제
- int크기
- java
- 파이썬배열
- androidstudio
- 자바연산자
- 백준
- 파이썬배열예제
Archives
- Today
- Total
발전을 위한 기록
[Python] 파이썬으로 txt 파일 단어 수 세기 본문
728x90
파이썬을 이용하여 텍스트 파일의 단어 빈도수를 분석할 수 있습니다.
주석 없는 코드
def count_word_frequency(text):
words = text.split()
frequency = {}
for word in words:
word = word.lower().strip(",.!?")
frequency[word] = frequency.get(word, 0) + 1
return frequency
def main():
file_path = 'c:\\Users\\USER\\Desktop\\abc.txt'
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read()
frequencies = count_word_frequency(text)
sorted_frequencies = sorted(frequencies.items(), key=lambda x: x[1], reverse=True)[:3]
print("\n단어 빈도수:")
for word, freq in sorted_frequencies:
print(f"{word}: {freq}")
if __name__ == "__main__":
main()
주석 있는 코드
# 단어 빈도수를 세는 함수를 정의합니다.
def count_word_frequency(text):
# 주어진 텍스트를 단어별로 분할합니다.
words = text.split()
# 빈도수를 저장할 빈 딕셔너리를 생성합니다.
frequency = {}
# 분할된 단어들을 순회하면서 빈도수를 세어 딕셔너리에 저장합니다.
for word in words:
# 단어를 소문자로 변환하고, 구두점을 제거합니다.
word = word.lower().strip(",.!?")
# 딕셔너리에 단어의 빈도수를 갱신하거나 추가합니다.
frequency[word] = frequency.get(word, 0) + 1
# 완성된 빈도수 딕셔너리를 반환합니다.
return frequency
# 메인 함수를 정의합니다.
def main():
# 읽을 파일의 경로를 지정합니다.
# 본인 파일 경로를 사용하셔야합니다!
file_path = 'c:\\Users\\USER\\Desktop\\파일이름.txt'
# 지정된 파일을 읽기 모드로 열고, 내용을 읽어옵니다.
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read()
# 읽어온 텍스트에 대해 단어 빈도수를 계산합니다.
frequencies = count_word_frequency(text)
# 계산된 빈도수를 내림차순으로 정렬하고 상위 10개를 선택합니다.
sorted_frequencies = sorted(frequencies.items(), key=lambda x: x[1], reverse=True)[:10]
# 단어 빈도수를 출력합니다.
print("\n단어 빈도수:")
for word, freq in sorted_frequencies:
print(f"{word}: {freq}")
# 파이썬 스크립트가 직접 실행될 때만 메인 함수를 실행합니다.
if __name__ == "__main__":
main()
TXT파일 만들기
예시 글은 Lorem Ipsum에서 가져왔습니다.
Lorem Ipsum - All the facts - Lipsum generator
What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type spec
www.lipsum.com
파일을 생성할 때 '.txt'를 붙이지 않고 생성해야 코드실행에 문제가 없습니다!
* 아닐수도..
출력 결과
728x90
'프로그래밍 > 파이썬' 카테고리의 다른 글
[Python] 파이썬으로 달력 만들기1 - <GUI> (0) | 2024.01.26 |
---|---|
[Python] 파이썬으로 파일 자동 분류하기 (0) | 2024.01.25 |
[Python] 파이썬 리스트 컴프리헨션(List Comprehension) (0) | 2024.01.23 |
[Python] 파이썬으로 리스트 길이 구하기 (0) | 2024.01.20 |
[Python] 파이썬 문자열 뒤집기 (0) | 2024.01.13 |