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

python文件排序的方法總結(jié)

 更新時間:2020年09月13日 10:42:04   作者:愛喝馬黛茶的安東尼  
在本篇內(nèi)容里小編給各位整理的是一篇關(guān)于python文件排序的方法總結(jié),有需要的朋友們可以參考下。

在python環(huán)境中提供兩種排序方案:用庫函數(shù)sorted()對字符串排序,它的對象是字符;用函數(shù)sort()對數(shù)字排序,它的對象是數(shù)字,如果讀取文件的話,需要進(jìn)行處理(把文件后綴名‘屏蔽')。

(1)首先:我測試的文件夾是/img/,里面的文件都是圖片,如下圖所示:

5e456c82768e849deb5d28f4bf56f0f.png

(2)測試庫函數(shù)sorted(),直接貼出代碼:

import numpy as np
import os
 
img_path='./img/'
 
img_list=sorted(os.listdir(img_path))#文件名按字母排序
img_nums=len(img_list)
for i in range(img_nums):
    img_name=img_path+img_list[i]
    print(img_name)

運行效果如下:

d1bae9b804c553b4d24a6e0381710b4.png

從圖片可以清晰的看出,文件名是按字符排序的。

(3)測試函數(shù)sort(),代碼:

import numpy as np
import os
img_path='./img/'
 
img_list=os.listdir(img_path)
img_list.sort()
img_list.sort(key = lambda x: int(x[:-4])) ##文件名按數(shù)字排序
img_nums=len(img_list)
for i in range(img_nums):
    img_name=img_path+img_list[i]
    print(img_name)

運行效果如下:

f2e1a74694600bcc7591d32a02c30ba.png

可以看出,文件名是按數(shù)字排序的;順便提下,sort函數(shù)中用到了匿名函數(shù)(key = lambda x:int(x[:-4])),其作用是將后綴名'.jpg'“屏蔽”(因為‘.jpg'是4個字符,所以[:-4]的含義是從文件名開始到倒數(shù)第四個字符為止),具體看python的匿名函數(shù)和數(shù)組取值方式。

實例擴(kuò)展:

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

到此這篇關(guān)于python文件排序的方法總結(jié)的文章就介紹到這了,更多相關(guān)python文件排序都有哪些方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python中的Unittest基本使用

    Python中的Unittest基本使用

    這篇文章主要介紹了Python中的Unittest基本使用,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-08-08
  • 使用Python實現(xiàn)將list中的每一項的首字母大寫

    使用Python實現(xiàn)將list中的每一項的首字母大寫

    今天小編就為大家分享一篇使用Python實現(xiàn)將list中的每一項的首字母大寫,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-06-06
  • Flask如何獲取用戶的ip,查詢用戶的登錄次數(shù),并且封ip

    Flask如何獲取用戶的ip,查詢用戶的登錄次數(shù),并且封ip

    這篇文章主要介紹了Flask如何獲取用戶的ip,查詢用戶的登錄次數(shù),并且封ip問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-01-01
  • Python常用圖像形態(tài)學(xué)操作詳解

    Python常用圖像形態(tài)學(xué)操作詳解

    這篇文章主要為大家詳細(xì)介紹幾個Python中常用的圖像形態(tài)學(xué)操作:腐蝕、膨脹、開閉運算、梯度運算、禮帽和黑帽,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2022-08-08
  • Python編程實現(xiàn)使用線性回歸預(yù)測數(shù)據(jù)

    Python編程實現(xiàn)使用線性回歸預(yù)測數(shù)據(jù)

    這篇文章主要介紹了Python編程實現(xiàn)使用線性回歸預(yù)測數(shù)據(jù),具有一定借鑒價值,需要的朋友可以了解下。
    2017-12-12
  • Python進(jìn)階之如何快速將變量插入有序數(shù)組

    Python進(jìn)階之如何快速將變量插入有序數(shù)組

    在我們學(xué)習(xí)python的過程中,學(xué)習(xí)序列是一門必修課。本文我們就來一起看一看Python是如何快速將變量插入有序數(shù)組的,感興趣的可以了解一下
    2023-04-04
  • Python自定義命令行參數(shù)選項和解析器

    Python自定義命令行參數(shù)選項和解析器

    這篇文章主要介紹了Python自定義命令行參數(shù)選項和解析器,本文主要使用的方法為argparse.ArgumentParser(),此模塊可以讓人輕松編寫用戶友好的命令行接口,程序定義它需要的參數(shù),需要的朋友可以參考下
    2023-07-07
  • Python3.x對JSON的一些操作示例

    Python3.x對JSON的一些操作示例

    最近在學(xué)習(xí)python3,正巧遇到了一些json的操作,索性整理一下分享出來,下面這篇文章主要給大家介紹了關(guān)于Python3.x對JSON的一些操作,需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-09-09
  • 講解python參數(shù)和作用域的使用

    講解python參數(shù)和作用域的使用

    本文會介紹如何將語句組織成函數(shù),還會詳細(xì)介紹參數(shù)和作用域的概念,以及遞歸的概念及其在程序中的用途。
    2013-11-11
  • 使用Python和OpenCV進(jìn)行圖像處理和分析

    使用Python和OpenCV進(jìn)行圖像處理和分析

    圖像處理和分析是計算機(jī)視覺領(lǐng)域的重要組成部分,本文將介紹如何使用Python編程語言和OpenCV庫進(jìn)行圖像處理和分析,我們將涵蓋圖像讀取、顯示、濾波、邊緣檢測和圖像分割等常見的圖像處理操作,并提供相應(yīng)的代碼示例
    2023-07-07

最新評論

淄博市| 兖州市| 五大连池市| 盐源县| 曲阳县| 聂拉木县| 内丘县| 仁怀市| 海伦市| 罗山县| 胶州市| 平乐县| 昆山市| 大埔县| 承德市| 弋阳县| 英山县| 灵山县| 阳春市| 安多县| 兴安县| 五指山市| 海口市| 平果县| 进贤县| 尤溪县| 论坛| 泽库县| 呼伦贝尔市| 株洲县| 峨眉山市| 潼南县| 海盐县| 山阴县| 麻城市| 万全县| 湘潭县| 全南县| 宁明县| 柯坪县| 肇源县|