当需要打印在一个句子中恰好出现 K 次的所有单词时,定义了一种使用 'split' 方法、'remove' 方法和 'count' 方法的方法。通过传递所需的参数来调用该方法并显示输出。
下面是相同的演示
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("字符串是:") print(my_string) print"The repeated words with frequency", " 是 :" key_freq_words(my_string, K)输出结果
字符串是: hi there how are you, how are u The repeated words with frequency 2 是 : how are
定义了一个名为“key_freq_words”的方法,它接受一个字符串和一个键作为参数。
该字符串基于空格拆分,并分配给一个列表。
这个列表被迭代,如果一个元素的计数等于键值,它就会显示在控制台上。
一旦它被打印出来,它就会从列表中删除。
在方法之外,定义了一个字符串,并显示在控制台上。
键的值已定义。
通过传递字符串和键来调用该方法。
输出显示在控制台上。