使用正则表达式从html文本中获取两个或更多连续的大写单词

时间:2017-01-12 19:34:49

标签: python regex

我正在尝试提取两个或多个单词的所有序列,其中每个单词的首字母大写。我认为'[A-Z][a-z]+(?=\s[A-Z])(?:\s[A-Z][a-z]+)+'会起作用,但它会添加我无法解释的字符。

这是完整的代码:

import re
import unittest
from bs4 import BeautifulSoup
html_page = """
<html>
<body>
<table>
<tr class=tb1><td>Lorem Ipsum dolor Sit amet</td></tr>
<tr class=tb1><td>Consectetuer adipiscing elit</td></tr>
<tr><td>Aliquam Tincidunt mauris eu Risus</td></tr>
<tr><td>Vestibulum Auctor Dapibus neque</td></tr>
</table>
</body>
</html>
"""

soup = BeautifulSoup(html_page)
text = soup.get_text()

def get_sequences(page):
    ex = re.compile('[A-Z][a-z]+(?=\s[A-Z])(?:\s[A-Z][a-z]+)+')
    sequences = re.findall(ex, page)
    return sequences

print get_sequences(text)

理想的结果应该是 ['Lorem Ipsum', 'Aliquam Tincidunt', 'Vestibulum Auctor Dapibus']

但相反,我得到了 [u'Lorem Ipsum', u'Aliquam Tincidunt', u' Risus\nVestibulum Auctor Dapibus']

3 个答案:

答案 0 :(得分:1)

这种方法是正确的,但没有指导。您正在寻找的是一行中的两个或多个连续大写单词。所以,你应该在文本中的行上运行正则表达式。这就是诀窍:

def get_sequences(page):
    ex = re.compile('[A-Z][a-z]+(?=\s[A-Z])(?:\s[A-Z][a-z]+)+')
    sequences = []
    for x in page.splitlines():
        sequences.append(re.findall(ex, x))
    sequences = sum(sequences,[])
    return sequences

答案 1 :(得分:0)

您可以使用以下内容:

((?:[A-Z][a-z]+\s*){2,})

https://regex101.com/r/EeS7F5/1示例

您还可以修改当前的正则表达式并摆脱前瞻

查看https://regex101.com/r/vViHXm/1

答案 2 :(得分:0)

Python代码:

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"[A-Z][a-z]+\s+[A-Z][a-z]+"

test_str = ("<html>\n"
    "<body>\n"
    "<table>\n"
    "<tr class=tb1><td>Lorem Ipsum dolor Sit amet</td></tr>\n"
    "<tr class=tb1><td>Consectetuer adipiscing elit</td></tr>\n"
    "<tr><td>Aliquam Tincidunt mauris eu Risus</td></tr>\n"
    "<tr><td>Vestibulum Auctor Dapibus neque</td></tr>\n"
    "</table>\n"
    "</body>\n"
    "</html>\n"
    "\"\"\"")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches):
    matchNum = matchNum + 1

    print (match.group())

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

<强>结果:

Lorem Ipsum
Aliquam Tincidunt
Vestibulum Auctor

请参阅: http://ideone.com/iQev8D