最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實現(xiàn)大文件排序的方法

 更新時間:2015年07月10日 12:26:42   作者:Sephiroth  
這篇文章主要介紹了Python大文件排序的方法,涉及Python針對文件、緩存及日期等操作的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下

本文實例講述了Python實現(xiàn)大文件排序的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:

import gzip
import os
from multiprocessing import Process, Queue, Pipe, current_process, freeze_support
from datetime import datetime
def sort_worker(input,output):
 while True:
  lines = input.get().splitlines()
  element_set = {}
  for line in lines:
    if line.strip() == 'STOP':
      return
    try:
      element = line.split(' ')[0]
      if not element_set.get(element): element_set[element] = ''
    except:
      pass
  sorted_element = sorted(element_set)
  #print sorted_element
  output.put('\n'.join(sorted_element))
def write_worker(input, pre):
  os.system('mkdir %s'%pre)
  i = 0
  while True:
    content = input.get()
    if content.strip() == 'STOP':
      return
    write_sorted_bulk(content, '%s/%s'%(pre, i))
    i += 1
def write_sorted_bulk(content, filename):
  f = file(filename, 'w')
  f.write(content)
  f.close()
def split_sort_file(filename, num_sort = 3, buf_size = 65536*64*4):
  t = datetime.now()
  pre, ext = os.path.splitext(filename)
  if ext == '.gz':
    file_file = gzip.open(filename, 'rb')
  else:
    file_file = open(filename)
  bulk_queue = Queue(10)
  sorted_queue = Queue(10)
  NUM_SORT = num_sort
  sort_worker_pool = []
  for i in range(NUM_SORT):
    sort_worker_pool.append( Process(target=sort_worker, args=(bulk_queue, sorted_queue)) )
    sort_worker_pool[i].start()
  NUM_WRITE = 1
  write_worker_pool = []
  for i in range(NUM_WRITE):
    write_worker_pool.append( Process(target=write_worker, args=(sorted_queue, pre)) )
    write_worker_pool[i].start()
  buf = file_file.read(buf_size)
  sorted_count = 0
  while len(buf):
    end_line = buf.rfind('\n')
    #print buf[:end_line+1]
    bulk_queue.put(buf[:end_line+1])
    sorted_count += 1
    if end_line != -1:
      buf = buf[end_line+1:] + file_file.read(buf_size)
    else:
      buf = file_file.read(buf_size)
  for i in range(NUM_SORT):
    bulk_queue.put('STOP')
  for i in range(NUM_SORT):
    sort_worker_pool[i].join()
   
  for i in range(NUM_WRITE):
    sorted_queue.put('STOP')
  for i in range(NUM_WRITE):
    write_worker_pool[i].join()
  print 'elasped ', datetime.now() - t
  return sorted_count
from heapq import heappush, heappop
from datetime import datetime
from multiprocessing import Process, Queue, Pipe, current_process, freeze_support
import os
class file_heap:
  def __init__(self, dir, idx = 0, count = 1):
    files = os.listdir(dir)
    self.heap = []
    self.files = {}
    self.bulks = {}
    self.pre_element = None
    for i in range(len(files)):
      file = files[i]
      if hash(file) % count != idx: continue
      input = open(os.path.join(dir, file))
      self.files[i] = input
      self.bulks[i] = ''
      heappush(self.heap, (self.get_next_element_buffered(i), i))
  def get_next_element_buffered(self, i):
    if len(self.bulks[i]) < 256:
      if self.files[i] is not None:
        buf = self.files[i].read(65536)
        if buf:
          self.bulks[i] += buf
        else:
          self.files[i].close()
          self.files[i] = None
    end_line = self.bulks[i].find('\n')
    if end_line == -1:
      end_line = len(self.bulks[i])
    element = self.bulks[i][:end_line]
    self.bulks[i] = self.bulks[i][end_line+1:]
    return element
  def poppush_uniq(self):
    while True:
      element = self.poppush()
      if element is None:
        return None
      if element != self.pre_element:
        self.pre_element = element
        return element
  def poppush(self):
    try:
      element, index = heappop(self.heap)
    except IndexError:
      return None
    new_element = self.get_next_element_buffered(index)
    if new_element:
      heappush(self.heap, (new_element, index))
    return element
def heappoppush(dir, queue, idx = 0, count = 1):
  heap = file_heap(dir, idx, count)
  while True:
    d = heap.poppush_uniq()
    queue.put(d)
    if d is None: return
def heappoppush2(dir, queue, count = 1):
  heap = []
  procs = []
  queues = []
  pre_element = None
  for i in range(count):
    q = Queue(1024)
    q_buf = queue_buffer(q)
    queues.append(q_buf)
    p = Process(target=heappoppush, args=(dir, q_buf, i, count))
    procs.append(p)
    p.start()
  queues = tuple(queues)
  for i in range(count):
    heappush(heap, (queues[i].get(), i))
  while True:
    try:
      d, i= heappop(heap)
    except IndexError:
      queue.put(None)
      for p in procs:
        p.join()
      return
    else:
      if d is not None:
        heappush(heap,(queues[i].get(), i))
        if d != pre_element:
          pre_element = d
          queue.put(d)
def merge_file(dir):
  heap = file_heap( dir )
  os.system('rm -f '+dir+'.merge')
  fmerge = open(dir+'.merge', 'a')
  element = heap.poppush_uniq()
  fmerge.write(element+'\n')
  while element is not None:
    element = heap.poppush_uniq()
    fmerge.write(element+'\n')
class queue_buffer:
  def __init__(self, queue):
    self.q = queue
    self.rbuf = []
    self.wbuf = []
  def get(self):
    if len(self.rbuf) == 0:
      self.rbuf = self.q.get()
    r = self.rbuf[0]
    del self.rbuf[0]
    return r
  def put(self, d):
    self.wbuf.append(d)
    if d is None or len(self.wbuf) > 1024:
      self.q.put(self.wbuf)
      self.wbuf = []
def diff_file(file_old, file_new, file_diff, buf = 268435456):
  print 'buffer size', buf
  from file_split import split_sort_file
  os.system('rm -rf '+ os.path.splitext(file_old)[0] )
  os.system('rm -rf '+ os.path.splitext(file_new)[0] )
  t = datetime.now()
  split_sort_file(file_old,5,buf)
  split_sort_file(file_new,5,buf)
  print 'split elasped ', datetime.now() - t
  os.system('cat %s/* | wc -l'%os.path.splitext(file_old)[0])
  os.system('cat %s/* | wc -l'%os.path.splitext(file_new)[0])
  os.system('rm -f '+file_diff)
  t = datetime.now()
  zdiff = open(file_diff, 'a')
  old_q = Queue(1024)
  new_q = Queue(1024)
  old_queue = queue_buffer(old_q)
  new_queue = queue_buffer(new_q)
  h1 = Process(target=heappoppush2, args=(os.path.splitext(file_old)[0], old_queue, 3))
  h2 = Process(target=heappoppush2, args=(os.path.splitext(file_new)[0], new_queue, 3))
  h1.start(), h2.start()
  old = old_queue.get()
  new = new_queue.get()
  old_count, new_count = 0, 0
  while old is not None or new is not None:
    if old > new or old is None:
      zdiff.write('< '+new+'\n')
      new = new_queue.get()
      new_count +=1
    elif old < new or new is None:
      zdiff.write('> '+old+'\n')
      old = old_queue.get()
      old_count +=1
    else:
      old = old_queue.get()
      new = new_queue.get()
  print 'new_count:', new_count
  print 'old_count:', old_count
  print 'diff elasped ', datetime.now() - t
  h1.join(), h2.join()

希望本文所述對大家的Python程序設(shè)計有所幫助。

相關(guān)文章

  • Python獲取與處理文件路徑/目錄路徑實例代碼

    Python獲取與處理文件路徑/目錄路徑實例代碼

    我們在用python進(jìn)行數(shù)據(jù)處理時往往需要將文件中的數(shù)據(jù)取出來做一些處理,下面這篇文章主要給大家介紹了關(guān)于Python獲取與處理文件路徑/目錄路徑的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-04-04
  • pandas?Dataframe實現(xiàn)批量修改值的方法

    pandas?Dataframe實現(xiàn)批量修改值的方法

    這篇文章主要介紹了pandas?Dataframe實現(xiàn)批量修改值的方法,在使用dataframe的時候?有時候會碰到需要批量修改數(shù)據(jù)的時候,下面文章主要說明兩種情況使用iloc對某幾行某幾列進(jìn)行全部修該和對數(shù)據(jù)進(jìn)行判定后,相互+/-/*某個數(shù),使用內(nèi)置函數(shù),需要的朋友可以參考一下
    2022-06-06
  • pytorch 模型可視化的例子

    pytorch 模型可視化的例子

    今天小編就為大家分享一篇pytorch 模型可視化的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • python 子類調(diào)用父類的構(gòu)造函數(shù)實例

    python 子類調(diào)用父類的構(gòu)造函數(shù)實例

    這篇文章主要介紹了python 子類調(diào)用父類的構(gòu)造函數(shù)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • python實現(xiàn)超時退出的三種方式總結(jié)

    python實現(xiàn)超時退出的三種方式總結(jié)

    這篇文章主要介紹了python實現(xiàn)超時退出的三種方式總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • python裝飾器類方法classmethod的使用場景

    python裝飾器類方法classmethod的使用場景

    這篇文章主要為大家介紹了python裝飾器類方法classmethod的使用場景,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-06-06
  • Python3中函數(shù)參數(shù)傳遞方式實例詳解

    Python3中函數(shù)參數(shù)傳遞方式實例詳解

    這篇文章主要介紹了Python3中函數(shù)參數(shù)傳遞方式,結(jié)合實例形式較為詳細(xì)的分析了Python3中函數(shù)參數(shù)傳遞的常見操作技巧,需要的朋友可以參考下
    2019-05-05
  • python二分法查找算法實現(xiàn)方法【遞歸與非遞歸】

    python二分法查找算法實現(xiàn)方法【遞歸與非遞歸】

    這篇文章主要介紹了python二分法查找算法實現(xiàn)方法,結(jié)合實例形式分析了Python使用遞歸與非遞歸算法實現(xiàn)二分查找的相關(guān)操作技巧,需要的朋友可以參考下
    2019-12-12
  • python tornado開啟多進(jìn)程的幾種方法

    python tornado開啟多進(jìn)程的幾種方法

    本文主要介紹了python tornado開啟多進(jìn)程的幾種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • Python深度學(xué)習(xí)pytorch神經(jīng)網(wǎng)絡(luò)多輸入多輸出通道

    Python深度學(xué)習(xí)pytorch神經(jīng)網(wǎng)絡(luò)多輸入多輸出通道

    這篇文章主要為大家介紹了Python深度學(xué)習(xí)中pytorch神經(jīng)網(wǎng)絡(luò)多輸入多輸出通道的詳解有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步
    2021-10-10

最新評論

蕉岭县| 浪卡子县| 安仁县| 日土县| 邛崃市| 滕州市| 黎川县| 白山市| 彭州市| 前郭尔| 河南省| 白朗县| 新民市| 项城市| 凤庆县| 固安县| 金湖县| 永兴县| 绥德县| 清河县| 桦南县| 屏南县| 太康县| 陆川县| 西和县| 克拉玛依市| 临沭县| 洪江市| 黄冈市| 阳信县| 乐平市| 定陶县| 铜陵市| 兴化市| 四子王旗| 安溪县| 海阳市| 静安区| 陈巴尔虎旗| 博罗县| 桐乡市|