Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python – ความถี่ของคำในสตริง (Word Frequency)


เมื่อต้องการหาความถี่ของคำโดยใช้ shorthand ของสตริง สามารถใช้ dictionary comprehension ได้

ตัวอย่าง

โค้ดสาธิตด้านล่าง

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}

คำอธิบาย

  • กำหนดสตริงและแสดงผลบนคอนโซล
  • ใช้ dictionary comprehension วนลูปผ่านสตริง แยกคำด้วยช่องว่าง
  • นับจำนวน 'key' และกำหนดให้ตัวแปร
  • แสดงตัวแปรเป็นผลลัพธ์บนคอนโซล