我想创建一个脚本来下载网页,转换一些代码(从HTML到TeX),然后将其打印到文件中。我得到了前两部分,但我不知道如何将其打印到文件中。
我使用正则表达式,但我听说过很多关于它们的坏事,但是......我怎么能用其中一个HTML解析器呢?
我列出了网址urllist
以及正则表达式列表regexlist
(第一项是搜索,第二项是替换)。我遍历所有这些并将每个url(在通过正则表达式转换后)保存到字典中的一个条目中。从那里,我想要做的是将字典的每个条目打印到不同的文件。
顺便说一下,如果你想用另一种语言展示另一种解决方案来展示它的美女,那么就可以毫无问题地做到这一点,我正在寻找不同的语言:)以及万一你在Python中回答,你可以通过使用良好的解决方案来优化它。
无论如何,这是我的代码。任何建议都会很棒(我在这种语言中是全新的,一般都是编程)。
import urllib
import re
outputpath = "~/Desktop/foo/"
webpath = "http://learnyouahaskell.com/"
namelist = [ "introduction",
"starting-out" ]
urllist = []
for i in range(len(namelist)):
urllist.append(webpath + namelist[i])
regexlist = [ [ r"^<!DOCTYPE([\s\S]+?)<h1" , "\\startweb\n\n<h1" ],
[ r"</p>[\s\n]*?<div class[\s\S]+?</script>\n</body>\n</html>", "</p>\n\n\\stopweb"],
[ r"<h1.*?>(.+?)</h1>" , r"\chapter{\1}\n" ],
[ r"<h2>(.+?)</h2>" , r"\section{\1}\n" ],
[ r"<i>(.+?)</i>" , r"\emph{\1}" ],
[ r"<em>(.+?)</em>" , r"\\bold{\1}" ],
[ "<p>", "\n" ], [ "</p>", "\n" ],
[ "<pre name=\"code\" class=\"haskell: (.+?)\">([\\s\\S]+?)\n?</pre>" , r"\n\starthaskell[\1]\2\n\stophaskell\n" ],
[ "\n\n\\haskell" , "\n\haskell" ],
[ "<span class=\"fixed\">(.+?)</span>" , r"\\typehaskell{\1}"],
[ "<span class=\"label function\">(.+?)</span>" , r"\\haskellfunction{\1}"],
[ "<span class=\"(class label|label class)\">(.+?)</span>" , r"\\haskellclass{\1}"],
[ "<span class=\"label type\">(.+?)</span>" , r"\\haskelltype{\1}"],
[ "<img src=\"(http://s3.amazonaws.com/lyah/)(.+?).png\" (alt|class)=\"(.+?)\" (class|alt)=\"(.+?)\" width=\"(\d+)\" height=\"(\d+)\">" , r"\n\placeimage[\2]{url=\1\2.png,\3=\4,\5=\6,width=\7pt,height=\8pt}\n" ],
[ "<a href=\"(.+?)\">(.+?)</a>" , r"\\url[\1]{\2}" ],
[ "<a.*?></a>", "" ],
[ "#" , "\#" ],
[ "&" , "&" ],
[ "…" , "\dots" ],
[ ">" , ">" ],
[ "<" , "<" ]
]
finaldoc = {}
for i in range(len(namelist)):
htmlfile = urllib.urlopen(urllist[i])
htmltext = htmlfile.read()
for regex in regexlist:
searchpattern = regex[0]
replacepattern = regex[1]
htmltext = re.sub(searchpattern, replacepattern, htmltext)
finaldoc[namelist[i]] = htmltext