我有一个名为data
的列表和一个名为word_count
的dict对象,在将频率转换为唯一整数之前,我想返回一个dict对象word_count
(预期格式:{'marjori': 1,'splendid':1...}
),然后对频率进行排序
data = [['marjori',
'splendid'],
['rivet',
'perform',
'farrah',
'fawcett']]
def build_dict(data, vocab_size = 5000):
word_count = {}
for w in data:
word_count.append(data.count(w)) ????
#print(word_count)
# how can I sort the words to make sorted_words[0] is the most frequently appearing word and sorted_words[-1] is the least frequently appearing word.
sorted_words = ??
我是Python新手,有人能帮我吗,提前谢谢。(我只想使用numpy
库和for循环。)
对于每个单词,如果它还不存在,则需要创建一个dict条目,如果它确实存在,则需要在其值中添加1:
然后,您可以按值对词典进行排序:
代码的最后一部分是不可理解的,但如果您只想计算单词数并将其插入字典,并按频率降序排序,我建议使用
defaultdict
并按如下方式实现:输出:
相关问题 更多 >
编程相关推荐