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

พิมพ์คำที่เกิดขึ้นในประโยคทุก K ครั้ง (Print Words Occurring Exactly K Times)


ตัวอย่าง

โค้ดด้านล่างหาคำที่ปรากฏในประโยคทุก K ครั้ง (K=2) โดย split แล้ววนลูป count และ remove เพื่อไม่พิมพ์ซ้ำ

def key_freq_words(my_string, K):
    my_list = list(my_string.split(" "))
    for i in my_list:
        if my_list.count(i) == K:
            print(i)
            my_list.remove(i)

my_string = "hi there how are you, how are u"
K = 2
print("The string is :")
print(my_string)
print("The repeated words with frequency", " are :")
key_freq_words(my_string, K)

ผลลัพธ์

The string is : hi there how are you, how are u
The repeated words with frequency 2 are : how are

คำอธิบาย

  • กำหนดฟังก์ชัน key_freq_words รับ string และ K

  • split string เป็นลิสต์คำ

  • วนลูปแต่ละคำ ถ้า count == K ให้ print และ remove ออกจากลิสต์ (กันพิมพ์ซ้ำ)

  • เรียกฟังก์ชันกับ string ตัวอย่าง K=2