将txt文件按符号python3

时间:2018-04-14 10:31:07

标签: python python-3.x

我有一个txt文件,大约1-10MB,像这样:

"Type,int_data,ID,..., some data"

我想用ID分隔它。 例如,执行以下操作:

list_1=[]
list_2=[]
list_3=[]
.. 
list_7=[]

with open(txt,'r', encoding='utf-8') as txt:                        
    for string in txt:
        string=string.rstrip().split(',')
        ID=int(string[2])
        if ID==1:
            list_1.append(string)
        elif ID==2:
            list_2.append(string)
            ..

但它很慢..它会更好吗?

2 个答案:

答案 0 :(得分:1)

这个怎么样?可能不会那么快,但试一试让我知道!

from collections import defaultdict
res = defaultdict(list) #making a dict of lists where ID is the key
with open(txt,'r', encoding='utf-8') as txt:                        
    for string in txt:
        res[string.split(',')[2]].append(string) #appending the lines to the ID key

答案 1 :(得分:1)

以下是我之前在100mb +文件上使用过的代码片段(我不是作者)。不确定它是否有助于您的文件大小或所有开销是否太多。基本上它是如何工作的首先是将文件分成多个字符块(chunkify),然后为每个块生成一个将从该块的开头到结尾读取的作业。然后将这些作业分发到您的线程池,以便您可以使用所有核心,同时高效地了解从它们发送接收数据的次数。

对于您的情况,只需为'process_wrapper'添加一个'process'函数,用于@Keerthi Bachu之类的每一行。

这可能有用,或者可能会给你一些启发。

import multiprocessing as mp,os

def process_wrapper(chunkStart, chunkSize):
    with open("input.txt") as f:
        f.seek(chunkStart)
        lines = f.read(chunkSize).splitlines()
        for line in lines:
            process(line)

def chunkify(fname,size=1024*1024):
    fileEnd = os.path.getsize(fname)
    with open(fname,'r') as f:
        chunkEnd = f.tell()
    while True:
        chunkStart = chunkEnd
        f.seek(size,1)
        f.readline()
        chunkEnd = f.tell()
        yield chunkStart, chunkEnd - chunkStart
        if chunkEnd > fileEnd:
            break

#init objects
pool = mp.Pool(cores)
jobs = []

#create jobs
for chunkStart,chunkSize in chunkify("input.txt"):
    jobs.append( pool.apply_async(process_wrapper,(chunkStart,chunkSize)) )

#wait for all jobs to finish
for job in jobs:
    job.get()

#clean up
pool.close()