怎么把文件移到html,查找和转换HTML文件并移动它们En-Masse

WReach..

8

以下代码可能会起到作用:

mapFileNames[source_, filenames_, target_] :=

Module[{depth = FileNameDepth[source]}

, FileNameJoin[{target, FileNameDrop[#, depth]}]& /@ filenames

]

htmlTreeToPlainText[source_, target_] :=

Module[{htmlFiles, textFiles, targetDirs}

, htmlFiles = FileNames["*.html", source, Infinity]

; textFiles = StringReplace[

mapFileNames[source, htmlFiles, target]

, f__~~".html"~~EndOfString :> f~~".txt"

]

; targetDirs = DeleteDuplicates[FileNameDrop[#, -1]& /@ textFiles]

; If[FileExistsQ[target], DeleteDirectory[target, DeleteContents -> True]]

; Scan[CreateDirectory[#, CreateIntermediateDirectories -> True]&, targetDirs]

; Scan[

Export[#[[2]], Import[#[[1]], "Plaintext"], "Text"] &

, Transpose[{htmlFiles, textFiles}]

]

]

使用示例(警告:首先删除目标目录!):

htmlTreeToPlainText["/users/me/web", "/users/me/desktop/bucket"]

这个怎么运作

FileName...在这种情况下,各种Mathematica 函数都很有用.首先,我们首先定义一个辅助函数mapFileNames,它接受一个源目录,一个位于源目录中的文件名列表,以及一个目标目录.它返回一个文件路径列表,用于命名目标目录下的相应位置.

mapFileNames[source_, filenames_, target_] :=

Module[{depth = FileNameDepth[source]}

, FileNameJoin[{target, FileNameDrop[#, depth]}]& /@ filenames

]

该函数用于FileNameDrop从每个文件名中删除前导源路径元素,FileNameJoin并将目标路径添加到每个结果的前面.要丢弃的前导元素的数量通过应用于FileNameDepth源路径来确定.

例如:

In[83]:= mapFileNames["/a/b", {"/a/b/x.txt", "/a/b/c/y.txt"}, "/d"]

Out[83]= {"/d/x.txt", "/d/c/y.txt"}

使用此函数,我们可以将源目录(source)下的HTML文件路径列表转换为目标目录(target)下的相应文本文件路径列表:

htmlFiles = FileNames["*.html", source, Infinity]

textFiles = StringReplace[

mapFileNames[source, htmlFiles, target]

, f__~~".html"~~EndOfString :> f~~".txt"

]

这些语句检索HTML文件列表,将它们映射到目标目录,然后将文件扩展名从更改.html为.txt.我们现在可以从生成的文本文件中提取必要的目录名称:

targetDirs = DeleteDuplicates[FileNameDrop[#, -1]& /@ textFiles]

再次FileNameDrop使用,这次是从每个文本文件的路径中删除文件名部分.

接下来,我们需要删除目标目录(如果它已经存在)并创建新的必需目录:

If[FileExistsQ[target], DeleteDirectory[target, DeleteContents -> True]]

Scan[CreateDirectory[#, CreateIntermediateDirectories -> True]&, targetDirs]

我们现在可以执行HTML到文本的转换,在知道目标目录已经存在的情况下是安全的:

Scan[

Export[#[[2]], Import[#[[1]], "Plaintext"], "Text"] &

, Transpose[{htmlFiles, textFiles}]

]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值