首页 > 解决方案 > 如何使用 Windows 批处理文件有效地将大量数据写入大型文本文件

问题描述

我有一个包含图像每个像素及其各自颜色的文本文件。我想提取具有特定颜色的每个像素坐标并将坐标快速放入文本文件中。一段时间后,我使用的代码变得非常慢。我需要从 220,000 个像素坐标中提取大约 80,000 个。我正在寻找一种有效的方法来从文本文件中提取大量数据,对其进行处理并将其放入文本文件中。

文本文件的布局:

“像素坐标 (x,y)” “rgb 作为 16 位值” “十六进制颜色代码” “颜色名称”

例子:

105,44: (0,32896,0)  #008000  green
106,44: (65535,0,0)  #FF0000  red
107,44: (65535,65535,65535,65535)  #FFFFFFFF  white
108,44: (0,0,0,65535)  #000000FF  black

这是我使用的代码:

echo off
SETLOCAL ENABLEDELAYEDEXPANSION
for /F "tokens=*" %%A in (temp.txt) do (
for /F "tokens=4,*" %%B in ("%%A") do (
::store coordinates of green pixels
if /i %%B==green (
for /F "tokens=1,*" %%C in ("%%A") do (

set Coordinate=%%C
set Coordinate=!Coordinate:~0,-1!
set Coordinate=!Coordinate:,= !
echo !Coordinate!>>greenPixels.txt
))))

如果我不将坐标附加到文本文件中,则代码运行速度相对较快。所以我正在寻找一种将变量快速附加到文本文件中的方法。我试图将所有坐标放入一个变量中,并在最后将该变量放入一个文本文件中。一段时间后,这也变得非常缓慢。

标签: batch-file

解决方案


为每一行打开目标文件,然后再次关闭它以再次打开下一行是非常无效的。而是一次性写入全部数据。此外,请尽早过滤数据,以便处理更少的数据。

只使用一个for循环,避免set变量管理。

@echo off
setlocal
(for /f "tokens=1,2 delims=,:" %%A in ('type temp.txt ^|find "green"') do (
   echo %%A %%B
))>greenPixels.txt

如果您需要为每种颜色创建文件(我感觉这就是您想要的):

@echo off
setlocal
(for /f "tokens=1,4 delims=: " %%A in (temp.txt) do (
   for /f "tokens=1,2 delims=," %%K in ("%%A") do (
      if "%%B" == "green" 1>&3 echo %%K %%L
      if "%%B" == "red"   1>&4 echo %%K %%L
      if "%%B" == "black" 1>&5 echo %%K %%L
      if "%%B" == "white" 1>&6 echo %%K %%L
   )  
)) 3>greenpixels.txt 4>redpixels.txt 5>blackpixels.txt 6>whitepixels.txt

This splits the colors into separate output streams inside the loop. Outside the loop these different streams are redirected to their corresponding files.

You can use stream 1 to 9, so you could split up to nine colors (for Stream 1 just skip the 1>&x part) so we are able to keep the efficient "write only once" method. I intentionally left out Stream 1 and 2, because they are reserved for STDOUT and STDERR, but nevertheless, they can be used the same way.

(about half a minute for ~238.000 lines of temp.txt)


推荐阅读