【问题标题】:Python: print/get first sentence of each paragraphPython:打印/获取每个段落的第一句
【发布时间】:2016-02-09 12:59:39
【问题描述】:

这是我的代码,但它会打印整个段落。如何只打印第一句,直到第一个点?

from bs4 import BeautifulSoup
import urllib.request,time

article = 'https://www.theguardian.com/science/2012/\
oct/03/philosophy-artificial-intelligence'

req = urllib.request.Request(article, headers={'User-agent': 'Mozilla/5.0'})
html = urllib.request.urlopen(req).read()

soup = BeautifulSoup(html,'lxml')

def print_intro():
    if len(soup.find_all('p')[0].get_text()) > 100:
        print(soup.find_all('p')[0].get_text())

此代码打印:

说明人脑具有的能力在某些情况下是 方面,远远优于那些在所有其他已知对象 宇宙将是无可争议的。大脑是唯一的对象 能够理解宇宙甚至存在,或者为什么存在 是无限多的素数,或者苹果掉落是因为 时空的曲率,或者服从其与生俱来的本能可以 在道德上是错误的,或者它本身存在。也不是独一无二的 能力仅限于这种大脑问题。冷酷的物理事实 是它是唯一可以推动自己进入的物体 空间和返回没有伤害,或预测和防止流星袭击 本身,或将物体冷却到绝对温度以上十亿分之一度 零,或跨银河系探测到其他同类。

但我只想打印:

说明人脑具有的能力在某些情况下是 方面,远远优于那些在所有其他已知对象 宇宙是无可争议的。

感谢您的帮助

【问题讨论】:

  • 获得第一个段落(即第一个

    元素)后,您可以将字符串拆分为字符串列表。 mystring.split(sep='.')。之后,您可以获得第一个列表元素。你可以试试这个吗?

  • 我得到了该 URL 的不同输出,'\n\nWednesday 3 October 2012 07.00\xa0BST\n\n\nLast modified on Sunday 10 January 2016 09.11\xa0GMT\n\n'。保存该文本的是 second <p> 标记。

标签: python text beautifulsoup bs4


【解决方案1】:

分割该点上的文本;对于单个拆分,使用 str.partition()str.split() 更快,但有限制:

text = soup.find_all('p')[0].get_text()
if len(text) > 100:
    text = text.partition('.')[0] + '.'
print(text)

如果您只需要处理 first <p> 元素,请改用 soup.find()

text = soup.find('p').get_text()
if len(text) > 100:
    text = text.partition('.')[0] + '.'
print(text)

但是,对于您给定的 URL,示例文本位于 second 段落中:

>>> soup.find_all('p')[1]
<p><span class="drop-cap"><span class="drop-cap__inner">T</span></span>o state that the human brain has capabilities that are, in some respects, far superior to those of all other known objects in the cosmos would be uncontroversial. The brain is the only kind of object capable of understanding that the cosmos is even there, or why there are infinitely many prime numbers, or that apples fall because of the curvature of space-time, or that obeying its own inborn instincts can be morally wrong, or that it itself exists. Nor are its unique abilities confined to such cerebral matters. The cold, physical fact is that it is the only kind of object that can propel itself into space and back without harm, or predict and prevent a meteor strike on itself, or cool objects to a billionth of a degree above absolute zero, or detect others of its kind across galactic distances.</p>
>>> text = soup.find_all('p')[1].get_text()
>>> text.partition('.')[0] + '.'
'To state that the human brain has capabilities that are, in some respects, far superior to those of all other known objects in the cosmos would be uncontroversial.'

【讨论】:

  • 谢谢大家。这行得通。但是,我不知道这一行中的“[0]”是做什么的……谁能解释一下?
  • @skeitel str.partition() 返回一个包含三个元素(头、分区字符串和尾)的元组,但我们只对其中的第一个值感兴趣。
  • 我现在明白了。谢谢
【解决方案2】:
def print_intro():
    if len(soup.find_all('p')[0].get_text()) > 100:
        paragraph = soup.find_all('p')[0].get_text()
        phrase_list = paragraph.split('.')
        print(phrase_list[0])

【讨论】:

  • 这不必要地拆分了超出需要的部分。至少限制拆分(str.split() 的第二个参数)。
【解决方案3】:

split 第一个period 的段落。参数1MAXSPLIT 不同,并节省您不必要的额外拆分时间。

def print_intro():
    if len(soup.find_all('p')[0].get_text()) > 100:
        my_paragraph = soup.find_all('p')[0].get_text()
        my_list = my_paragraph.split('.', 1)
        print(my_list[0])

【讨论】:

    【解决方案4】:

    您可以使用find('.'),它返回您要查找的内容的第一次出现的索引。

    所以如果段落存储在一个名为paragraph的变量中

    sentence_index = paragraph.find('.')
    # add the '.'
    sentence += 1
    print(paragraph[0: sentence_index])
    

    显然这里缺少控制部分,例如检查 paragraph 变量中包含的字符串是否有 '.'等等。无论如何,如果 find() 没有找到您要查找的子字符串,则返回 -1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 2022-11-27
      • 2018-03-06
      • 2016-04-06
      • 2020-10-09
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多