根据文档文本字符串批量重命名文件

2 投票
2 回答
1499 浏览
提问于 2025-04-17 22:35

我看到有一个叫做 Bulk Rename Utility 的工具,但我想重命名的数据文件比较私密,所以我有点担心使用这个工具。再加上,我不确定它能否按照我想要的方式找到特定的字符串来重命名文件。因此,我在想有没有其他差不多的办法,能保证我的文件保持私密。如果没有,我也愿意听听大家使用 Bulk Rename Utility 的经验。谢谢!

补充说明:虽然我在编程方面还是个新手,但我对编程相关的解决方案非常开放。另外,我要说明的是,所有需要处理的文件都是 .html 文件。

更新:

像这样的代码能用吗?

 for file in directory:
 f = fopen(file, 'r')
 line = f.readLine();
 while(line):
  if(line.strip() == '<th style="width: 12em;">Name:</th>'):
   nextline = f.readLine().strip();
   c = nextline.find("</td>")
   name = nextline[4:c]
   os.commandline(rename file to name)
   break
  line = f.readLine()

我还有什么需要注意的地方,以确保这段代码在 Python 中运行良好吗?

更新:示例 html

<html> <body>
   <h1 style="text-align: right;">[TITLE]</h1>
    <div style="font-size: 12pt;">
      <div style="float: left;">[NUMBER]</div>
      <div style="float: right;">[DATE]</div>
      <div style="clear: both;" />
    </div>
    <hr />
    <h3>[INFO]</h3>
    <table class="text" cellspacing="0" cellpadding="0" border="0">
      <tr>
        <th style="width: 12em;">Name:</th>
        <td>[NAME]</td>
      </tr> </body> </html>

2 个回答

1

用PowerShell和命令提示符像个高手一样更改文件名,具体方法可以参考这个链接。

http://www.howtogeek.com/111859/how-to-batch-rename-files-in-windows-4-ways-to-rename-multiple-files/

在阅读完整个页面之前,不要急着下结论。

2

抱歉,你的问题不太清楚。我看了好几遍,猜测你想要一个方法(可能是一个Windows批处理.bat文件),这个方法应该:

  • 允许用户输入搜索字符串。
  • 处理多个.html格式的文件。
  • 在每个文件中查找搜索字符串第一次出现后下一行中,<td></td>标签之间的内容,并用这个内容来重命名文件。

下面的批处理文件就是用来做这个处理的:

@if (@CodeSection == @Batch) @then

@echo off

set /P "search=Enter search string: "
for /F "delims=" %%a in ('dir /B /A-D *.html') do (
   for /F "delims=" %%b in ('cscript //nologo //e:jscript "%~F0" "%%a"') do (
      if "%%b" neq "NoNameFound" (
         ECHO ren "%%a" "%%b"
      ) else (
         echo ERROR: No name found in file "%%a"
      )
   )
)
goto :EOF

@end

var file = new ActiveXObject("Scripting.FileSystemObject").OpenTextFile(WScript.Arguments.Item(0)),
    search = WScript.CreateObject("WScript.Shell").Environment("Process")("search"),
    re = new RegExp(search+".+\n.+<td>(.+)<\/td>",""), result;

if (result = re.exec(file.ReadAll())) {
   WScript.Stdout.WriteLine(result[1]);
} else {
   WScript.Stdout.WriteLine("NoNameFound");
}
file.Close();

这是用你提供的数据得到的输出:

C:\> test
Enter search string: <th style="width: 12em;">Name:</th>
ren "input.html" "[NAME]"

注意,这个批处理文件只是显示ren命令,但并没有执行它!你需要在ren前面去掉ECHO部分,才能真正执行这个命令。

如果我遗漏了什么,请在评论中告诉我,修改我的说明。

撰写回答