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}]
]