【问题标题】:Type error when trying to sort a list from a file尝试从文件中对列表进行排序时键入错误
【发布时间】:2017-10-09 00:47:48
【问题描述】:

在 Python 中,我试图返回:

  • 唯一词的排序列表
  • 文件中出现次数的计数

我不断收到错误:

TypeError:“int”和“str”的实例之间不支持“

我的代码如下:

def countWords(ifile):
    lst1=[]
    infile=open(ifile,'r')
    lines=(inifle.read()).lower()
    for element in lines.split():
        lines.replace(',',' ')
        sct=lines.count(element)
        lst1.append(element)
        lst1.append(sct)
    return lst1.sort()
    infile.close()

我做错了什么?

【问题讨论】:

  • 该错误告诉您出了什么问题:您正在尝试对包含字符串和数字的列表进行排序。 9'dog' 应该被认为更大?
  • 'dog' 会被认为更大
  • 如果您的问题得到解答,您可以accept the most helpful one

标签: python list file sorting count


【解决方案1】:

我正在尝试返回唯一单词的排序列表和计数 文件中出现的次数。

我建议使用 collections.Counter 数据结构 - 它的主要目的是计数。

from collections import Counter

def countWords(ifile):
    c = Counter()
    with open(ifile) as f:
        for line in f:
            c.update(line.strip().split())

    return c.most_common()

most_common 按降序或频率返回单词出现次数。不需要进一步排序。


如果你的文件足够小,你可以稍微压缩一下你的函数:

def countWords(ifile):
    with open(ifile) as f:
        c  = Counter(f.read().replace('\n', ' ').split())
    return c.most_common()

【讨论】:

    【解决方案2】:

    脚本不好,问题出在排序上。 当您尝试对“str”和“int”进行排序时,您会收到此错误。 如果您不尝试对其进行排序,该脚本可以正常工作,并且在另一个说明中您应该在返回列表之前关闭文件。

    【讨论】:

    • 问题是我必须在一个列表中对两者进行排序。单词必须先出现,然后是出现次数。
    • 是否必须使用列表进行操作?您可以使用字典来更有效地满足您的目的,因为“单词”可以用作键,而计数可以用作“值”
    猜你喜欢
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 2021-02-01
    • 2014-08-31
    • 2016-03-06
    相关资源
    最近更新 更多