【问题标题】:Text file parsing fastest as possible文本文件解析尽可能快
【发布时间】:2019-02-08 07:14:00
【问题描述】:

我有一个非常大的文件,其中包含如下行:

....

0.040027 a b c d e 12 34 56 78 90 12 34 56

0.050027 f g h i l 12 34 56 78 90 12 34 56

0.060027 a b c d e 12 34 56 78 90 12 34 56

0.070027 f g h i l 12 34 56 78 90 12 34 56

0.080027 a b c d e 12 34 56 78 90 12 34 56

0.090027 f g h i l 12 34 56 78 90 12 34 56

....

我需要以最快的方式拥有如下字典。

我使用以下代码:

ascFile = open('C:\\eample.txt', 'r', encoding='UTF-8')

tag1 = ' a b c d e '

tag2 = ' f g h i l '

tags = [tag1, tag2]

temp = {'k1':[], 'k2':[]}

key_tag = {'k1':tag1, 'k2':tag2 }

t1 = time.time()

for line in ascFile:

    for path, tag in key_tag.items():

        if tag in line:

            columns = line.strip().split(tag, 1)

            temp[path].append([columns[0], columns[-1].replace(' ', '')])

t2 = time.time()

print(t2-t1)

我在 6 秒内解析一个 360MB 的文件有以下结果,我想改进一下时间。

temp = {'k1':[['0.040027', '1234567890123456'], ['0.060027', '1234567890123456'], ['0.080027', '1234567890123456']], 'k2':[['0.050 ', '1234567890123456'], ['0.070027', '1234567890123456'], ['0.090027', '1234567890123456']] }

【问题讨论】:

  • 您是否尝试过存储元组列表而不是列表列表?它们应该更轻量级,因此创建速度更快。

标签: python file parsing text


【解决方案1】:

我假设您在文件中有固定数量的单词作为您的键。使用split 断开字符串,然后从拆分列表中取出一个片段来直接计算您的密钥:

import collections

# raw strings don't need \\ for backslash:
FILESPEC = r'C:\example.txt'

lines_by_key = collections.defaultdict(list)

with open(FILESPEC, 'r', encoding='UTF-8') as f:
    for line in f:
        cols = line.split()
        key = ' '.join(cols[1:6])
        pair = (cols[0], ''.join(cols[6:]) # tuple, not list, could be changed
        lines_by_key[key].append(pair)

print(lines_by_key)

【讨论】:

  • 字数可以从 0 变为 8。无论如何我得到 6 秒
  • 无论如何我有 6 秒的时间来减慢目标
【解决方案2】:

我使用了分区而不是拆分,以便“in”测试和拆分可以一次性完成。

for line in ascFile:

    for path, tag in key_tag.items():

        val0, tag_found, val1 = line.partition(tag)

        if tag_found:
            temp[path].append([val0, val1.replace(' ', '')])
            break

您的 360MB 文件会更好吗?

你也可以做一个简单的测试,你所做的就是一次循环遍历文件一行:

for line in ascFile:
    pass

这将告诉您您的最佳时间是什么时候。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    相关资源
    最近更新 更多