Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在海量文本文件上使用正则表达式的内存限制_Python_Regex - Fatal编程技术网

Python 在海量文本文件上使用正则表达式的内存限制

Python 在海量文本文件上使用正则表达式的内存限制,python,regex,Python,Regex,我有一个以下格式的文本文件: ('1', '2') ('3', '4') . . . 我想让它看起来像这样: 1 2 3 4 etc... 我一直在尝试使用python中的re模块来实现这一点,方法是将re.sub命令链接在一起,如下所示: for line in file: s = re.sub(r"\(", "", line) s1 = re.sub(r",", "", s) s2 = re.sub(r"'", "", s1)

我有一个以下格式的文本文件:

('1', '2')
('3', '4')
     .
     .
     .
我想让它看起来像这样:

1 2
3 4
etc...
我一直在尝试使用python中的re模块来实现这一点,方法是将re.sub命令链接在一起,如下所示:

for line in file:
    s = re.sub(r"\(", "", line)
    s1 = re.sub(r",", "", s)
    s2 = re.sub(r"'", "", s1)
    s3 = re.sub(r"\)", "", s2)
    output.write(s3)
output.close()
在我接近输出文件的末尾之前,它似乎工作得很好;然后它变得不一致并停止工作。我想这是因为我处理的文件太大了;300MB或大约1200万条线路


有人能帮我确认一下我的内存不足吗?或者是别的什么?合适的替代方案,或者解决方法?

为什么不将它们作为python元组加载,并使用。您也可以使用
with
语句在块末尾关闭文件,而不是手动打开和关闭文件:

With open(file_name) as input,open(output_name,'w') as output:
    for line in input:
       output.write(','.join(ast.literal_eval(line.strip())))

您可以使用一个更简单的正则表达式来简化代码,该正则表达式可以查找输入中的所有数字:

import re
with open(file_name) as input,open(output_name,'w') as output:
for line in input:
       output.write(' '.join(re.findall('\d+', line))
       output.write('\n')
为了更好的表现,我会用a。代码变得更具可读性

# Python 3

from collections import namedtuple
from ast import literal_eval
#...

Row = namedtuple('Row', 'x y')
with open(in_file, 'r') as f, open(out_file, 'w') as output:
    for line in f.readlines():
        output.write("{0.x} {0.y}".
                     format(Row._make(literal_eval(line))))

这是一种不使用re模块的方法:

in_file = open(r'd:\temp\02\input.txt', 'r')
out_file = open(r'd:\temp\02\output.txt', 'w')

for line in in_file:
    out_file.write(line.replace("'", '').replace('(', '').replace(', ', ' ').replace(')', ''))
out_file.close()

看起来您的文件中满是表示整数的两个字符串元组的表示-为什么?!您可以
ast.literal\u eval
每一行,然后使用
csv
将其写出来。它正在逐行处理文件,因此我不认为文件的大小会导致问题。您确定您的代码中没有其他东西创建isue吗?您可以使用单个正则表达式:
输出。写入(re.sub(r“\(\s*”(\d+),\s*”(\d+),\s*\”,r“\1\2”,行))
。但正如我所说,这不是你的问题。您可能需要显示更多的代码才能获得该特定问题的答案。我遇到了此错误(我的第一行有35个字符长):r=行。_make(line)File“”,第21行,in _maketypeerror:需要2个参数,得到35@EliRiekeberg可以更新以修复此问题-答案现在使用@Kasramvd提到的
ast.literal\u eval
进行转换,它将字符串行转换为元组,以便在
namedtuple
中输入,并合并
output.write()