【问题标题】:Write delimited strings from an infile to an outfile将分隔字符串从输入文件写入输出文件
【发布时间】:2013-08-01 22:22:39
【问题描述】:

目的是搜索一个 infile (html) 并在一个可以传递给 wget 的 outfile 中重现任何图像的 URL。这将是我用 Python 编写的第一个有用的东西,它似乎在 Fedora 上运行良好。我在任何地方都找不到像这样的东西。有人对此有改进建议吗?

import fileinput
import re
#replace 'output.txt' with the name of your outfile
file = open('output.txt', 'w')

#prefix and postfix are how we discriminate your substring from the infile's line
prefix = '<img src='
postfix = '.jpg'

#read through the infile line-by-line
for line in fileinput.input():
    if re.search(prefix, line):
        #from if above, if you find the prefix, assign the integer to first_index
        first_index = line.index(prefix)
            if re.search(postfix, line):
                #same as comment above, but for postfix
                second_index = line.index(postfix)
                #write your string plus an newline to the outfile
                file.write(line[first_index+prefix.__len__():second_index+postfix.__len__()]+'\n')

【问题讨论】:

  • 那会是尝试用我闻到的正则表达式解析 HTML 吗?
  • wget -prl1 --accept=jpg &lt;url&gt;
  • 我确实喜欢 wget,但它总是比我要求的要多。 Wget 也经常抱怨一些 url 并拒绝做这项工作。它仍然是我的第一选择。

标签: python string slice file-io


【解决方案1】:

我过去做过类似的事情,效果很好......我相信它会比尝试使用正则表达式解析更准确。

from HTMLParser import HTMLParser


class ImageFinder(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.file = open('output.txt', 'w') 
    def handle_starttag(self, tag, attrs):
        if tag == "img":
            url = [u[1] for u in attrs if u[0] == "src"][0]
            self.file.write(url+"\n")
    def __exit__(self):
        self.file.close()

inputdata = open("myfile.txt").read()
parser = ImageFinder()
parser.feed(inputdata)

【讨论】:

  • 啊,更清洁的解决方案!
猜你喜欢
  • 1970-01-01
  • 2014-10-18
  • 1970-01-01
  • 2021-07-13
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多