【问题标题】:How to parse sentences into tokens with either regex or toolkits如何使用正则表达式或工具包将句子解析为标记
【发布时间】:2014-05-05 02:17:19
【问题描述】:

如何使用正则表达式或 beautifulsoup、lxml 等工具包解析这样的句子:

input = """Yesterday<person>Peter Smith</person>drove to<location>New York</location>"""

进入这个:

Yesterday
<person>Peter Smith</person>
drove
to
<location>New York</location>

我不能使用re.findall("&lt;person&gt;(.*?)&lt;/person&gt;", input),因为标签不同。

【问题讨论】:

  • 您可以使用竖线 (|) 在正则表达式中查找多重模式,例如:((.*?)|(.)*)
  • 嵌套标签呢?如果你有它们应该是什么输出?

标签: python regex xml-parsing beautifulsoup lxml


【解决方案1】:

试试这个正则表达式 -

>>> import re
>>> input = """Yesterday<person>Peter Smith</person>drove to<location>New York</location>"""
>>> print re.sub("<[^>]*?[^/]\s*>[^<]*?</.*?>",r"\n\g<0>\n",input)
Yesterday
<person>Peter Smith</person>
drove to
<location>New York</location>

>>> 

正则表达式here的演示

【讨论】:

  • @DevEx 很高兴为您提供帮助 :)
【解决方案2】:

看看使用BeautifulSoup是多么容易:

from bs4 import BeautifulSoup

data = """Yesterday<person>Peter Smith</person>drove to<location>New York</location>"""

soup = BeautifulSoup(data, 'html.parser')
for item in soup:
    print item

打印:

Yesterday
<person>Peter Smith</person>
drove to
<location>New York</location>

UPD(将非标签项拆分为空格并在新行上打印每个部分):

soup = BeautifulSoup(data, 'html.parser')
for item in soup:
    if not isinstance(item, Tag):
        for part in item.split():
            print part
    else:
        print item

打印:

Yesterday
<person>Peter Smith</person>
drove
to
<location>New York</location>

希望对您有所帮助。

【讨论】:

  • 谢谢@alecxe,我如何在新行上打印每个项目:drove \n to\n
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-23
相关资源
最近更新 更多