【问题标题】:how to use for loop and split() function to count the frequency of key words search in python [closed]如何使用for循环和split()函数来计算python中关键字搜索的频率[关闭]
【发布时间】:2022-10-04 17:24:07
【问题描述】:

我有一个这样的列表列表: [[123,'我的新书','我的新电脑'],[456,'她的旧鞋']...]

我的任务是计算关键词“我的”、“你的”的频率,并创建另一个类似这样的列表: [[123,'我的新书','我的新电脑',2],[456,'她的旧鞋',0]...]。

我是 python 新手,并且有一些使用 for 循环和 split() 来实现它的想法。在多个嵌套的 for 循环中停留了几个小时,我需要帮助。谢谢。

【问题讨论】:

    标签: python regex loops


    【解决方案1】:

    尝试

    LoL = [[123, 'my new book','my new computer'],[456,'her old shoes']]
    
    LoLwithCounts = []
    for item in LoL:
        cnt = 0
        for subitem in item:
            if isinstance(subitem, str):
                word_list = subitem.split()
                if 'my' in word_list or 'your' in word_list:
                    cnt+=1
        LoLwithCounts.append(item+[cnt])
    print(LoLwithCounts)
    

    【讨论】:

    • 这也将计算单词“yourself”和“army”。
    • 好点子。更新代码以避免这种情况。
    猜你喜欢
    • 2019-06-04
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 2021-01-30
    • 2021-06-13
    相关资源
    最近更新 更多