gpt4 book ai didi

python - 计算Python中的常用词

转载 作者:太空宇宙 更新时间:2023-11-04 10:06:17 25 4
gpt4 key购买 nike

def words(word,number):
if number<len(word):
result={}
for key,value in word.items():
common_num=sorted(set(word.values()), reverse=True)[:number]
if value in common_num:
result.update({key:value})
word.clear()
word.update(result)
new_word_count={}
common_word=[]
common=[]
for key, value in word.items():
if value in common_word:
common.append(value)
common_word.append(value)
new_word_count=dict(word)
for key,value in new_word_count.items():
if value in common:
del word[key]

例子:

>>> word={'a': 2, 'b': 2, 'c' : 3, 'd: 3, 'e': 4, 'f' : 4, 'g' : 5}
>>> words(word,3)

我的输出:{'g': 5}

预期输出:{'g': 5, 'e': 4, 'f': 4}

知道为什么我得到这个输出

最佳答案

好吧,没有任何特殊的导入,有更简单的方法来完成您想要做的事情。在跟踪和存储所保留的值,然后删除,然后重新添加时,您会遇到很多繁琐的事情,而您可以简化很多事情;即使有解释性评论,这也大大缩短了:

def common_words(word_count, number):
# Early out when no filtering needed
if number >= len(word_count):
return

# Get the top number+1 keys based on their values
top = sorted(word_count, key=word_count.get, reverse=True)[:number+1]

# We kept one more than we needed to figure out what the tie would be
tievalue = word_count[top.pop()]

# If there is a tie, we keep popping until the tied values are gone
while top and tievalue == word_count[top[-1]]:
top.pop()

# top is now the keys we should retain, easy to compute keys to delete
todelete = word_count.keys() - top
for key in todelete:
del word_count[key]

有一些更好的方法可以避免在 word_count 中重复查找(排序 items,而不是 keys,等等),但是这更容易理解 IMO,并且 word_count 中的额外查找是有界的和线性的,所以这没什么大不了的。

关于python - 计算Python中的常用词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40856218/

25 4 0
文章推荐: 具有多个方法和构造函数的 Java Box 程序
文章推荐: jquery - 在多个
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com