gpt4 book ai didi

batch-file - 如何使用 .bat 格式将 unicode 文件批量格式化为 ANSI 文件?

转载 作者:行者123 更新时间:2023-12-03 20:10:33 25 4
gpt4 key购买 nike

.bat 编程的初学者,所以请耐心等待:我一直在尝试将从科学仪器收集的大量 Unicode 文件数据库转换为 ANSI 格式。此外,我需要将所有这些文件转换为 .txt 文件。

现在,第二部分非常简单——我过去常常使用“批量重命名实用程序”来完成它,我想到目前为止我已经能够让它工作了。

第一部分应该很简单,我发现了多个不同的类似问题,但它们似乎都是针对 powershell 的, a single file ,或者结束对正在使用的特定编码的长时间讨论。 One question seems to match mine exactly ,但在尝试了他们建议的代码后,似乎只有一半文件传输正常,另一半作为无意义代码通过。我一直在使用代码:

for %%F in (*.001) do ren "*SS.001" "*SS1.001"

for %%F in (*.001) do type "%%F" >"%%~nF.txt"

然后删除/移动多余的文件。

我过去已经成功地手动转换了文件(左),但当前的编码似乎失败了(右): Side by side comparison of files encoded by hand vs by program

我的问题是:

  1. 我从仪器中获得的单个文件是否可能在多种编码(部分 UTF-8,部分 UTF-16),这是搞乱我的程序(或者更有可能,我使用的编码是太小)?如果是这样的话,我就会明白为什么特别像平方和度数符号这样的字符被破坏了,但是不是数据,它只是数字。
  2. 我的代码中是否有一些明显的拼写错误导致了这种奇怪的情况错误?
  3. 如果错误可能嵌入了什么 unicode(8 对 16 对 32)或我正在使用 ANSI(1252 vs ???),我该如何检查?
  4. 我如何修复此代码才能正常工作?

如果有任何更好的问题我应该问或我需要添加其他信息,请告诉我。谢谢!!

最佳答案

Is it possible that a single file I get from my instrument is in multiple encodings (part UTF-8, part UTF-16), and that this is messing up my program (or more likely, i'm using an encoding that is too small)?

我不相信一个文件可以包含多种编码。

Is there some obvious typo in my code that is causing this bizarre error?

cmd 环境可以很容易地处理不同的代码页,但它很难处理多字节编码和字节顺序标记。实际上,这是尝试读取 UCS-2 LE 中返回的 WMI 结果时的常见问题。虽然存在 a pure batch workaround为了清理 WMI 结果,不幸的是它并不适用于所有其他编码。

If the error might be embedded in what unicode (8 vs 16 vs 32) or ANSI (1252 vs ???) I'm using, how would I check? How would I fix this code to work?

.NET 更擅长理智地处理未知编码的文件。 StreamReader class ,当它读取第一个字符时,将读取 BOM 并自动检测文件编码。我知道您希望避免使用 PowerShell 解决方案,但 PowerShell 确实是访问 IO 方法以透明地处理这些文件的最简单方法。

不过,有一种简单的方法可以将 PowerShell 混合代码合并到批处理脚本中。用 .bat 扩展名保存它,看看它是否符合您的要求。

<# : batch portion
@echo off & setlocal

powershell -noprofile "iex (${%~f0} | out-string)"
goto :EOF
: end batch / begin PowerShell hybrid #>

function file2ascii ($infile, $outfile) {

# construct IO streams for reading and writing
$reader = new-object IO.StreamReader($infile)
$writer = new-object IO.StreamWriter($outfile, [Text.Encoding]::ASCII)

# copy infile to ASCII encoded outfile
while (!$reader.EndOfStream) { $writer.WriteLine($reader.ReadLine()) }

# output summary
$encoding = $reader.CurrentEncoding.WebName
"{0} ({1}) -> {2} (ascii)" -f (gi $infile).Name, $encoding, (gi $outfile).Name

# Garbage collection
foreach ($stream in ($reader, $writer)) { $stream.Dispose() }
}

# loop through all .001 files and apply file2ascii()
gci *.001 | %{
$outfile = "{0}\{1}.txt" -f $_.Directory, $_.BaseName
file2ascii $_.FullName $outfile
}

虽然确实可以使用 get-contentout-file cmdlet 简化此过程,但上面演示的 IO 流方法将避免您必须加载将整个数据文件放入内存中——如果您的任何数据文件很大,这将是一个好处。

关于batch-file - 如何使用 .bat 格式将 unicode 文件批量格式化为 ANSI 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42774941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com