【问题标题】:Nested for-loop iteration stops嵌套的 for 循环迭代停止
【发布时间】:2014-11-05 15:19:58
【问题描述】:

我有两个输入文件:一个 html 文件和一个 css 文件。我想根据css文件的内容对html文件进行一些操作。

我的html是这样的:

<html>
 <head>
        <title></title>
    </head>
    <body>
    <p class = "cl1" id = "id1"> <span id = "span1"> blabla</span> </p>
    <p class = "cl2" id = "id2"> <span id = "span2"> blablabla</span> <span id = "span3"> qwqwqw </span> </p>
    </body>
    </html>

span id 的样式在 css 文件中定义(每个 span id 单独定义!)

在做真正的事情之前(根据他们的风格删除跨度),我试图从 html 中打印出 id,并从与每个 id 对应的 css 中打印出样式描述。

代码:

from lxml import etree

tree = etree.parse("file.html")

filein = "file.css"


def f1():

    with open(filein, 'rU') as f:   
        for span in tree.iterfind('//span'):   
            for line in f:
                if span and span.attrib.has_key('id'):
                    x = span.get('id')
                    if "af" not in x and x in line:
                            print x, line
def main():
     f1() 

所以,有两个 for 循环,如果分开,它们会完美地迭代,但是当放在这个函数中时,迭代会在第一个循环后停止:

>> span1 span`#span1 { font-weight: bold; font-size: 11.0pt; font-style: normal; letter-spacing: 0em } 

我该如何解决这个问题?

【问题讨论】:

    标签: python for-loop iteration lxml


    【解决方案1】:

    如果我认为树已完全加载到内存中,您可以尝试反转循环。这样,您只需浏览文件filein 一次:

    def f1():
    
        with open(filein, 'rU') as f:   
            for line in f:
                for span in tree.iterfind('//span'):   
                    if span and span.attrib.has_key('id'):
                        x = span.get('id')
                        if "af" not in x and x in line:
                                print x, line
    

    【讨论】:

      【解决方案2】:

      这是因为您已经阅读了所有文件行,直到第二个外循环开始。 为了使它工作,你需要在 filein 开始内部循环之前添加 f.seek(0):

      with open(filein, 'rU') as f:   
          for span in tree.iterfind('//span'):
              f.seek(0)   
              for line in f:
                  if span and span.attrib.has_key('id'):
                      x = span.get('id')
                      if "af" not in x and x in line:
                              print x, line
      

      【讨论】:

      • 感谢您的提示!我不知道这个搜索功能。 спасибо))
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多