Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python – 문자열의 단어 빈도


문자열 속기를 사용하여 단어의 빈도를 찾아야 할 때 사전 이해를 사용할 수 있습니다.

아래는 동일한 데모입니다.

my_str = 'Hi there Will, how are you Will, Will you say Hi to me'
print("The string is : " )
print(my_str)
my_result = {key: my_str.count(key) for key in my_str.split()}
print("The word frequency is : ")
print(my_result)

출력

The string is :
Hi there Will, how are you Will, Will you say Hi to me
The word frequency is :
{'Hi': 2, 'there': 1, 'Will,': 2, 'how': 1, 'are': 1, 'you': 2, 'Will': 3, 'say': 1, 'to': 1, 'me': 1}

설명

  • 문자열이 정의되고 콘솔에 표시됩니다.

  • 사전 이해는 문자열을 반복하고 공백을 기준으로 분할하는 데 사용됩니다.

  • 'key'의 개수가 결정되어 변수에 할당됩니다.

  • 이 변수는 콘솔에 출력으로 표시됩니다.