>  기사  >  백엔드 개발  >  Python 3.3을 사용하여 단어 빈도를 계산하고 발생순으로 정렬하는 방법

Python 3.3을 사용하여 단어 빈도를 계산하고 발생순으로 정렬하는 방법

Barbara Streisand
Barbara Streisand원래의
2024-10-21 21:40:03837검색

How to Count Word Frequencies and Sort by Occurrence Using Python 3.3

단어 빈도 계산 및 발생 빈도별 정렬

말씀하신 대로 목표는 두 개의 목록을 만드는 것입니다. 하나는 고유한 단어에 대한 목록이고 다른 하나는 개별 단어에 대한 목록입니다. 빈도의 오름차순으로 정리된 단어와 함께 각각의 빈도입니다. 접근 방식의 개요를 제공했지만 Python 3.3을 사용하여 세부 정보를 채워 보겠습니다.

Python 3.3에는 카운터나 사전과 같은 내장 메커니즘이 포함되어 있지 않으므로 간단한 루프를 사용하여 다음을 수행합니다. 원하는 결과를 얻으세요.

<code class="python"># Create lists to store unique words and their counts
unique_words = []
frequencies = []

# Iterate over the original list of words
for word in original_list:
    # Check if the word is already in the unique words list
    if word not in unique_words:
        # If not, add the word to the unique words list and initialize its frequency to 1
        unique_words.append(word)
        frequencies.append(1)
    else:
        # If the word is already in the list, increment its frequency
        frequencies[unique_words.index(word)] += 1

# Sort the unique word list based on the frequencies list
sorted_words = [word for _, word in sorted(zip(frequencies, unique_words), reverse=True)]

# Output the sorted list of unique words
print(sorted_words)</code>

이 코드는 단어 빈도를 효율적으로 계산하고 그에 따라 고유 단어를 정렬하여 정렬된 고유 단어 목록으로 출력을 전달합니다.

위 내용은 Python 3.3을 사용하여 단어 빈도를 계산하고 발생순으로 정렬하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.