【问题标题】:Regex to capitalize paragraphs in HTML python正则表达式在 HTML python 中大写段落
【发布时间】:2015-09-09 18:40:59
【问题描述】:

我想获取 HTML 文档中的所有内容并将句子大写(在段落标签内)。输入文件的所有内容全部大写。

我的尝试有两个缺陷 - 首先,它删除了段落标签本身,其次,它只是将匹配组中的所有内容都小写。我不太清楚 capitalize() 是如何工作的,但我认为它会使句子的第一个字母......大写。

也可能有比正则表达式更简单的方法来做到这一点。这是我所拥有的:

import re

def replace(match):
    return match.group(1).capitalize()

with open('explanation.html', 'rbU') as inf:
    with open('out.html', 'wb') as outf:
        cont = inf.read()
        par = re.compile(r'(?s)\<p(.*?)\<\/p')
        s = re.sub(par, replace, cont)
        outf.write(s)

【问题讨论】:

  • 首先,不要使用正则表达式来提取p标签的内容,使用Beautifulsoup。
  • 我只是想做一些快速简单的一次性使用。我通常不接触 HTML。
  • 永远不要在 HTML/XML 上使用正则表达式,因为同样的情况,StackOverflow 用户会发疯。 stackoverflow.com/a/1732454/1066393
  • Beautifulsoup 又快又简单,没问题。
  • 关于capitalize(),不管是不是句子,都会把第一个字母大写。提取句子的一种可能方法是使用 nltk。

标签: python html regex python-2.7


【解决方案1】:

beautifulsoupnltk 的示例:

from nltk.tokenize import PunktSentenceTokenizer
from bs4 import BeautifulSoup

html_doc = '''<html><head><title>abcd</title></head><body>
<p>i want to take everything in an HTML document and capitalize the sentences (within paragraph tags).
the input file has everything in all caps.</p>
<p>my attempt has two flaws - first, it removes the paragraph tags, themselves, and second, it simply lower-cases everything in the match groups.
 i don't quite know how capitalize() works, but I assumed that it would leave the first letter of sentences... capitalized.</p>
<p>there may be a much easier way to do this than regex, too. Here's what I have:</p>
</body>
<html>'''

soup = BeautifulSoup(html_doc, 'html.parser')

for paragraph in soup.find_all('p'):
    text = paragraph.get_text()
    sent_tokenizer = PunktSentenceTokenizer(text)
    sents = [x.capitalize() for x in sent_tokenizer.tokenize(text)]
    paragraph.string = "\n".join(sents)

print(soup)

【讨论】:

  • 如何将其写入字符串?它说它必须是一个缓冲区,而不是 BeautifulSoup。
  • 要定位特定位置(之前、之后、内部...的段落,具有 x、y 或 z 属性),您可以使用带有 beautifulsoup 的 css 选择器(请参阅文档)。另一种可能的方法是使用lxml 模块而不是允许使用xpath 查询的beautifulsoup
  • 如果想要最终结果为字符串,只需要str(soup)
猜你喜欢
  • 2016-04-02
  • 2010-09-12
  • 1970-01-01
  • 2011-02-09
  • 1970-01-01
  • 2014-08-05
  • 2017-01-23
  • 1970-01-01
相关资源
最近更新 更多