尝试从文件中排序列表时键入错误

时间:2017-10-09 00:47:48

标签: python list file sorting count

在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()

我做错了什么?

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

脚本不好,问题在于排序。 您正在尝试排序' str'和' int'。 如果您不尝试对其进行排序,该脚本可以正常工作,而在另一个注释中,您应该在返回列表之前关闭该文件。