2017-10-09 59 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()