batch-file - 如何使用 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
))))
如果我不将坐标附加到文本文件中,则代码运行速度相对较快。所以我正在寻找一种将变量快速附加到文本文件中的方法。我试图将所有坐标放入一个变量中,并在最后将该变量放入一个文本文件中。一段时间后,这也变得非常缓慢。
解决方案
为每一行打开目标文件,然后再次关闭它以再次打开下一行是非常无效的。而是一次性写入全部数据。此外,请尽早过滤数据,以便处理更少的数据。
只使用一个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
)
推荐阅读
- javascript - Vue:如何在挂载钩子之前使用 mapState 的值?
- typescript - VueJS 编译失败:找不到依赖项
- html - 标签未在文本输入上方的左上角对齐
- rust - Rust:无法垃圾收集增量编译会话目录
- python - 码头工人 | 烧瓶+Redis | 烧瓶没有启动
- reactjs - React 中的悬停效果太慢(悬停效果的状态更新)
- java - 使用 SwitchMaterial 切换按钮推送通知
- mysql - Power Bi 错误代码:28 - 设备上没有剩余空间
- jquery - 我使用 Asp.net Webform Listbox 作为选择。1)有没有办法在 Sumoselect 中包含删除/取消选择图标“X”(如附加的魔法搜索图像)?
- reactjs - 使用 react.js 以电子邮件形式发送警报