【问题标题】:Find the most frequent words that appear in the dataset查找数据集中出现频率最高的单词
【发布时间】:2020-07-22 19:22:05
【问题描述】:

我编写了一个函数,它接受一个列表作为输入并返回列表中最常见的项目。

##Write the function
def most_frequent(List): 
    dict = {} 
    count, itm = 0, '' 
    for item in reversed(List): 
        dict[item] = dict.get(item, 0) + 1
        if dict[item] >= count : 
            count, itm = dict[item], item 
    return(item) 
  
    return num 

# verfiy the code 

list = [5,42,34,6,7,4,2,5]
print(most_frequent(list)) 

然后下载两个文本文件以获取最常用的单词。

# Download the files restaurants.txt and restaurant-names.txt from Github
!curl https://raw.githubusercontent.com/ipeirotis/introduction-to-python/master/data/restaurant-names.txt -o restaurant-names.txt
!curl https://raw.githubusercontent.com/ipeirotis/introduction-to-python/master/data/restaurants.txt -o restaurants.txt



# create the list from the restaurants.txt
  List = open("restaurants.txt").readlines()

# get the most most frequent restaurant names
print("The most frequent restaurant names is ",most_frequent(List))

print(most_common(List))

但是当我尝试查找出现在餐厅名称中的最常用词时。我得到了同样的结果。你能帮忙检查一下这是否正确吗?谢谢

 # create the list from the restaurants.txt
List = open("restaurants.txt").readlines()

# get the most most frequent restaurant names
print("The most frequent restaurant names is ",most_frequent(List))

【问题讨论】:

标签: python list


【解决方案1】:

它是return itm(最常见的项目)而不是return item(反向列表的最后一部分)

【讨论】:

    【解决方案2】:

    您似乎为餐厅名称文件使用了错误的文件名。从你的 curl 命令来看:

    !curl https://raw.githubusercontent.com/ipeirotis/introduction-to-python/master/data/restaurant-names.txt -o restaurant-names.txt

    您应该使用的文件名是restaurant-names.txt,因此您的代码应该是:

     # create the list from the restaurants.txt
    List = open("restaurants-names.txt").readlines()
    
    # get the most most frequent restaurant names
    print("The most frequent restaurant names is ",most_frequent(List))
    

    【讨论】:

    • 感谢您的回复。然而,这不是错误。再次感谢
    【解决方案3】:

    可能是函数出错了,如果你尝试相同的测试数据但顺序不同,例如:list = [42,5,34,6,5,7,4,2]而不是list = [5,42,34,6,7,4,2,5],输出仍然是5吗?

    【讨论】:

    • 你是对的。它返回 42。我是 python 新手。你能帮忙指出错误吗?谢谢
    • 您将最常见的项目存储在itm 变量中,对吧?所以你可以只用return itm 而不是return item
    猜你喜欢
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多