【问题标题】:Looping stops after the first item in the list循环在列表中的第一项之后停止
【发布时间】:2014-02-17 16:02:15
【问题描述】:
places = []
persons = []    
unknown = []
newlist = []
filename = 'file.html' 
tree = etree.parse(filename)
input_file = open(filename, 'rU')
def extract(tree):   
     <some code>
    return places
    return persons
    return unknown

def change_class():
 extract(tree)  

 for line in input_file:        
    for x in places:
         for z in unknown:                                                                       

            if x+'</dfn>' in line:

                    newline = line.replace('"person"', '"place"')
                    newlist.append(newline)

            elif z+'</dfn>' in line:

                    newline = line.replace('"person"','"undefined"')
                    newlist.append(newline)
            else:
                newlist.append(line)

            break
         break

 for x in newlist:
    print x

我有一个带有错误类值的此类 html 文件:

 <html>
  <head></head>
  <body>
    <p class ='person'><dfn>New-York</dfn>
    <p class = 'place'><dfn>John Doe</dfn>
    <p class ='person'><dfn>Paris</dfn>
    <p class = 'place'><dfn>Jane Doe</dfn>
  </body>
</html>

我的脚本允许我重新打印同一个文件,但它只替换两个列表(地点和未知)的第一项的类值:

 <html>
  <head></head>
  <body>
    <p class ='place'><dfn>New-York</dfn>
    <p class = 'unknown'><dfn>John Doe</dfn>
    <p class ='person'><dfn>Paris</dfn>
    <p class = 'place'><dfn>Jane Doe</dfn>
  </body>
</html>

然后它有点停止迭代两个列表并直接进入 else 步骤并将所有其余部分添加到新列表中而无需替换。 Python 没有报错,使用 extract() 函数也成功提取了列表,我检查了...

【问题讨论】:

  • 为什么不用正则表达式?
  • 好吧,你在没有任何条件的情况下打破了两个内部循环。那么为什么你会期望不止一个循环呢?
  • 我应该在哪里使用它们?
  • 完全不要使用它们
  • 如果没有两个中断,它将进入无限循环

标签: python list loops iteration


【解决方案1】:
known_places = #list of known places
unkowns = #list of unknown places and persons

newlist = []
for line in input_file:
    if any(place in line for place in Known_places):
        line = line.replace("person", "place")
    elif any(unkown in line for unkown in unkowns):
        line = line.replace("person","undefined")
    newlist.append(line)

这样的事情可能会奏效。

【讨论】:

    【解决方案2】:

    我删除了我的另一个答案,因为它试图解决你没有的问题。我看到您已经接受了答案,但也请查看 BeautifulSoup 解决方案。

    from bs4 import BeautifulSoup
    
    PLACES = ["New-York","Paris"] # etc
    PEOPLE = ["John Doe","Jane Doe"] # etc
    
    soup = BeautifulSoup(open('file.txt'))
    paragraphs = soup("p") # grabs all the <p>...</p> elements
    for p in paragraphs:
        if p.dfn.string in PLACES:
            p['class'] = 'place'
        elif p.dfn.string in PEOPLE:
            p['class'] = 'person'
    

    str(soup) 现在是您的 HTML 文档,可根据要求进行修改。

    【讨论】:

    • 感谢您的回答!看起来很有趣,我之前从未使用过 BeautifulSoup...
    • @elaine_blath BeautifulSoup 是一个了不起的 XML/HTML 解析器。我自己还在学习它,但应用程序令人难以置信! :)
    猜你喜欢
    • 2012-01-07
    • 1970-01-01
    • 2023-03-28
    • 2021-09-15
    • 2019-01-11
    相关资源
    最近更新 更多