2017-10-09 63 views
-3

在Python排序列表时类型错误时,我试图返回:试图从一个文件

  • 唯一字
  • 发生次数的文件中的计数排序列表

我不断收到错误:

TypeError: '<' not supported between instances of 'int' and '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

错误告诉你什么是错的:你试图理清同时包含字符串和数字的列表。什么应该考虑更大'9'或''狗'? – Julien

+0

'狗'将被视为更大 –

+0

如果您的问题得到解答,您可以[接受最有帮助的](https://stackoverflow.com/help/someone-answers)。 –

回答

0

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

+0

问题是我必须在列表中排序两个。这个词必须先出现,然后是出现次数。 –

+0

使用列表来强制使用它吗?你可以使用一个字典来更有效地适合你的目的,因为'单词'可以用作键,计数可以'值' – nishgaba

1

I am trying to return a sorted list of unique words and the count of the number of occurrences within a file.

我建议使用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()