Python 将分隔字符串从填充文件写入输出文件

Python 将分隔字符串从填充文件写入输出文件,python,string,slice,file-io,Python,String,Slice,File Io,其目的是搜索一个内嵌(html)并在一个输出文件中重现可以传递给wget的任何图像的URL。这将是我用Python编写的第一个有用的东西,而且它似乎在Fedora上运行良好。我在任何地方都找不到这样的东西。有人对这方面的改进有什么建议吗 import fileinput import re #replace 'output.txt' with the name of your outfile file = open('output.txt', 'w') #prefix and postfix

其目的是搜索一个内嵌(html)并在一个输出文件中重现可以传递给wget的任何图像的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')
导入文件输入
进口稀土
#将“output.txt”替换为输出文件的名称
文件=打开('output.txt','w')
#前缀和后缀是我们区分子字符串和填充线的方式

prefix='我过去做过类似的事情,效果非常好。。。我相信这会比用正则表达式解析更准确

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)

那会不会是试图用我闻到的正则表达式解析HTML?
wget-prl1--accept=jpg
我确实喜欢wget,但它总是比我要求的多。Wget还经常抱怨一些url,并拒绝这样做。这仍然是我的第一次尝试。啊,更干净的解决方案!