【问题标题】:two functions not working in the same script, but working separately两个函数不在同一个脚本中工作,而是单独工作
【发布时间】:2014-01-27 17:19:00
【问题描述】:

我正在编写一个用于解析此类 html 文档的脚本:

<html>
  <head></head>
  <body>
     <p>
       <dfn>text</dfn>sometext<i>othertext</i></p>
     <p> .....................................</p>
     <p> .....................................</p>
  </body>
</html>

我尝试了不同的 xml 解析包并在 lxml 上停止。 我需要先迭代dfn 标记的内容,然后使用正则表达式迭代i 标记的内容。因此,我为每个任务编写了 2 个函数。它们分开工作,但不能在同一个脚本中一起工作。他们在这里:

tree = etree.parse(html-file)

def f1():
   for x in tree.getiterator('dfn'):
       bu = x.text
       if re.findall(r'\s[A-Z]{1,2}$', bu):                  
           print(bu)

def f2():
    for x in tree.getiterator('i'):
       mu = x.text
       if re.findall(r'\W\s[A-Z]$', mu):
           print(mu)


def main():
    f1()
    f2()

if __name__ == "__main__":
    main() 

当我运行脚本时,我得到 f1 的正确输出,然后是以下错误消息:

Traceback (most recent call last):
  File "/home/elaine/Desktop/try2.py", line 47, in <module>
    main()
  File "/home/elaine/Desktop/try2.py", line 33, in main
    f1()
  File "/home/elaine/Desktop/try2.py", line 20, in f1
    if re.findall(r'\s[A-Z]{1,2}$', bu):                  
  File "/usr/lib/python2.7/re.py", line 177, in findall
    return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer

【问题讨论】:

  • 如果您首先调用f2,它是否会为您提供正确的输出,然后是f1 的错误?

标签: python function xml-parsing lxml


【解决方案1】:

你不需要测试x.text是否不是None吗?

【讨论】:

    【解决方案2】:

    仔细查看堆栈跟踪,尤其是这一行:

    File "/home/elaine/Desktop/try2.py", line 20, ***in f1***
    

    这告诉您错误发生在您的f1 函数中。如果你注释掉对f2 的调用,你应该会发现你仍然得到同样的错误。看起来 f1 正确完成,因为它为您提供了正确的输出,但它最后一定遇到了导致它中断的东西。

    我建议将print(bu) 放在bu = x.text 行之后,以查看bu 的值是什么导致正则表达式中断。 bu 可能是 None,尽管它也有可能采用其他值。

    如果您需要更多帮助,我建议发布您尝试解析的 html 文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-19
      • 2016-06-19
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 2018-07-26
      • 1970-01-01
      相关资源
      最近更新 更多