【问题标题】:TypeError: '<' not supported between instances of 'dict' and 'int'TypeError:'dict'和'int'的实例之间不支持'<'
【发布时间】:2021-01-15 08:55:29
【问题描述】:

我刚开始学习 Python,目前正在尝试计算分段中字符序列的频率(分段为单词)。我的count_seq 函数有问题。在这个函数中,我希望在第一个循环中获取分段的每个段(in_object),然后在第二个循环中计算序列。 从我试图改变和理解的内容来看,我认为问题肯定出在for idx in range 循环中。 问题是这样的,当我尝试运行脚本时,我有这个 TypeError :“TypeError: '

def main():
    seq_length = 3
    freq_dict = count_seq(in_object, seq_length)
    print_freq(freq_dict)


def count_seq(segmentation, seq_length):
    freq_dict = dict()


    for idx in range(len(segmentation)):
        freq_dict[idx] = dict()
        segments = segmentation[idx].get_content()

    for pos in range(len(segments)):
        char = segments[pos:pos+seq_length]
        if len(char) < seq_length:
            continue
        freq_dict[char] = freq_dict.get(char, 0)+1
    return freq_dict


def print_freq(freq_dict):
    """Recuperer le contenu de la fonction de l'exercice 2..."""
    for key in sorted(freq_dict, key=freq_dict.get, reverse=True):
        print("%s:%s" %(key, freq_dict[key]))




if __name__ == "builtins":
    if in_objects:
        main()

【问题讨论】:

标签: python loops sequence text-segmentation


【解决方案1】:

当您调用sorted 时会发生此错误。项目的排序方式是将它们相互比较。你的freq_dict 的一些值是dicts,其中一些是ints,不能相互比较(小于:7 还是字典?没有意义)。

如果要按这种方式排序,则需要确保freq_dict 中的所有值都是可比较的类型。

在此块中,您将一堆键设置为空字典:

for idx in range(len(segmentation)):
    freq_dict[idx] = dict()

然后在下一个循环中,将另一组键设置为ints。

freq_dict 最后的目标是什么?

【讨论】:

  • 最后应打印freq_dict,并显示每个序列及其对应的频率。
  • 我不清楚你为什么要在开始时用dicts 填充它,或者你希望通过第一个循环完成什么。由于我们不知道 segmentation 是什么,因此很难为您提供修复建议。
猜你喜欢
  • 1970-01-01
  • 2019-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
  • 2018-09-03
  • 2020-11-13
相关资源
最近更新 更多