如何在使用 Python 指定的 delims 后查找和 replace/remove 文本?

How to find and replace/remove text after a specified delims with Python?

我有一个 40GB 文本文件包含以下行:

55655653:foo

6654641:balh2

我写了一个批处理脚本来查找 replace/remove :foo 并且只保留之前的数字。

批处理脚本:

 @echo on

 ((for /f "tokens=1 delims=:" %%b in (C:\data.txt) do ( echo %%b)) >C:\dataFinal.txt
 )
pause

批处理的问题是无法读取40GB的大文件

所以我决定编写 Python 代码来做同样的事情 :

f1 = open('data.txt', 'r')
f2 = open('dataFinal.txt', 'w')
for line in f1:
    f2.write(line.replace(':', ''))
f1.close()
f2.close()

我在这里缺少的是如何指定: 之后的文本也被删除,对于批处理文件,它是 tokens=1 delims=:

请注意文件大小

我已经使用 Java 代码生成了 40GB 的文件(也许此信息可以帮助我们解决某些问题):

BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
while (in.ready()) {
   String line = in.readLine();
   PrintStream out = new PrintStream(System.out, true, "UTF-8");
   out.println(initializeKeyPair(line).toString() + ":" + line );

你应该使用 line.split():

>>> line = '55655653:foo'
>>> line, _ = line.split(':', 1)
>>> print(line)
55655653

请注意,这也会剪切尾部 '\n',因此您应该手动添加它(或使用打印)。此外,这样的 line, _ = line.split(':', 1) 可能引发异常 : is not in the line.

所以你的代码会像这样:

f1 = open('data.txt', 'r')
f2 = open('dataFinal.txt', 'w')
for line in f1:
    line, _ = line.split(':', 1)
    f2.write(line + '\n')
f1.close()
f2.close()

(请注意,Jon Clements 提供了更漂亮的文件处理方式)。

您可以使用str.partition拆分第一个:

之前的数字
with open('data.txt') as fin, open('dataFinal.txt', 'w') as fout:
    fout.writelines(line.partition(':')[0] + '\n' for line in fin)

不是我们在这里使用 with 所以文件会自动关闭并且生成器表达式循环 fin 拆分行,占用第一个 : 然后写入它返回 fout 并附加一个换行符。

您可能希望指定编码:

import io

with io.open('/usr/share/dict/words', encoding='utf-8') as fin, io.open('dataFinal.txt', 'w', encoding='utf-8') as fout:
    fout.writelines(line.partition(':')[0] + '\n' for line in fin)

您可以使用此方法通过批处理文件轻松处理任何大小的数据文件:

@echo off

rem Use a subroutine to read from C:\data.txt and write to C:\dataFinal.txt
rem the subroutine must be in a separate .bat file and must be called via CMD.EXE

cmd /C call ProcessFile.bat  < C:\data.txt  > C:\dataFinal.txt
pause

这是ProcessFile.bat:

@echo off
setlocal EnableDelayedExpansion

rem Process lines of input file in an endless loop
for /L %%i in ( ) do (

   rem Read next line and check for EOF
   set "line="
   set /P "line="
   if not defined line exit /B

   rem Process line read
   for /F "delims=:" %%b in ("!line!") do echo %%b

)

请注意,此方法在第一个空行处结束读取输入文件,但如果需要,可以修复此点。