打印句子中出现 K 次的所有单词
pythonserver side programmingprogramming更新于 2025/10/28 20:28:17
当需要打印句子中出现 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"出现频率为", "的重复单词为:"
key_freq_words(my_string, K)
输出
字符串为: hi there how are you, how are u 出现频率为 2 的重复单词为: how are
解释
名为‘key_freq_words’ 的方法被定义为以字符串和键为参数。
字符串根据空格进行拆分,并分配给列表。
此列表被迭代,如果元素的数量等于键值,则显示在控制台上。
打印后,将其从列表中删除。
在方法之外,定义了一个字符串,并显示在控制台上。
定义了键的值。
通过传递字符串和键来调用该方法。
输出显示在控制台上。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

