簡體   English   中英

從巨大的文本文件中列出前 5 個大數字的最佳方法

[英]Best way to list top 5 large numbers from a huge text file

試圖找到最好和最簡單的方法來列出 150G 文本文件中的前 5 個數字。

我正在搜索的文件每行中只有數字,如下所示。

456789876
098765
36
48987
4509876
.
.
.

嘗試了下面的程序,它仍然只顯示數字中的第一個數字,而不是完整的數字。

from heapq import nlargest

data=open('number.txt','r')
text=data.read()
print (text)
print nlargest(5, (text))
data.close()

有沒有其他方法可以選擇前 5 名?

您沒有將數據視為數字。 相反,您將整個文件內容(一個非常大的字符串)傳遞給nlargest() ,它只能按字典順序為您提供最后一個字符。 在這種情況下,字符'9'在字符'8'之后。

您需要 a) 逐行讀取您的輸入,而不是一個大字符串,並且 b) 將您的數據轉換為整數,以便它們通過數值進行比較:

from heapq import nlargest

def as_numbers(it):
    for line in it:
        try:
            yield int(line)
        except ValueError:
            # not a line with a number, skip
            continue

with open('number.txt') as data:
    five_largest = nlargest(5, as_numbers(data))                
    print(five_largest)

我在這里使用了一個生成器函數將行轉換為整數,因為這樣可以更容易地繼續使用heapq.nlargest() (這絕對是用於這項工作的正確工具,因為它可以有效地保持頂部 - n 個值在 O(NlogK) 時間內可用,因此對於固定的 K=5 項,它基本上是線性的並且僅與文件中的整數值數量成正比)。 生成器函數負責轉換為int() ,跳過任何無法轉換的行。

還要注意使用with與打開的文件對象; with塊的末尾,文件會自動為您關閉,無需在此處顯式調用data.close() 即使有例外也會如此!

演示:

>>> from heapq import nlargest
>>> from io import StringIO
>>> random_data = '\n'.join([str(random.randrange(10**6)) for _ in range(10000)])  # 10k lines of random numbers between 0 and 1 million
>>> random_data.splitlines(True)[1042:1045] # a few sample lines
['39909\n', '15068\n', '420171\n']
>>> sample_file = StringIO(random_data)  # make it a file object
>>> def as_numbers(it):
...     for line in it:
...         try:
...             yield int(line)
...         except ValueError:
...             # not a line with a number, skip
...             continue
...
>>> nlargest(5, as_numbers(sample_file))
[999873, 999713, 999638, 999595, 999566]

輸入:

456789876
098765
36
48987
4509876
563456
47345734
6234
67456
235423
7348
3
656    

代碼:

data=open('number.txt','r')
text=data.readlines()#read the file line to line and introduce in a list of string
numbers = map(int, text)#convert the list of string in list of int
numbers.sort()#sort your list
print (numbers[-5:])#print the 5 largest
print (numbers[:5])#print the 5 smaller

結果:

[235423, 563456, 4509876, 47345734, 456789876]
[3, 36, 656, 6234, 7348]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM