如何获取歌词歌曲中最常用的50个单词(Python)

2024-04-29 16:36:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我试图在歌词中返回最多50个常用词,我有一个问题,我真的不明白为什么会发生这种情况

代码中的名称“歌词”是来自文本文件的歌词字符串。循环的每一次迭代都是不同的歌词串,我需要将它们包含在歌曲中显示的单词总数中

如果有人知道问题出在哪里,并能提供帮助,那就太好了

my output is not with words is in characters: "[(' ', 46), ('o', 24), ('e', 23), ('n', 15), ('t', 15), ('h', 12), ('a', 12), ('w', 8), ('r', 8), ('s', 8), ('\n', 7), ('f', 7), ('d', 6), ('u', 5), ('y', 5), ('m', 5), ('I', 4)..." and i need to get something like: ("the", 555), ("you", 365)... without include white spaces and \n

    count = {}
    for songs in the_dict.values():
        songs = songs[0]
        for lyrics in songs.values():
            lyrics = lyrics[2]
            count = Counter(lyrics)
    return count.most_common(50)

Tags: andthe代码in名称foriscount
2条回答

您应该在每个空格和换行符处拆分歌词,这样您就可以得到一个单词数组(而不是像现在这样立即解析字符串)

所以你应该使用

lyrics = lyrics[2].split()

在计数之前调用lyrics上的split()方法:

split_lyrics = lyrics[2].split()
count = Counter(split_lyrics)

https://www.geeksforgeeks.org/find-k-frequent-words-data-set-python/

相关问题 更多 >