Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:打印/获取每个段落的第一句话_Python_Text_Beautifulsoup_Bs4 - Fatal编程技术网

Python:打印/获取每个段落的第一句话

Python:打印/获取每个段落的第一句话,python,text,beautifulsoup,bs4,Python,Text,Beautifulsoup,Bs4,这是我的代码,但它打印了整个段落。如何只打印第一句话,直到第一个点 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':

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

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())
此代码打印:

说明人脑在某些方面 远高于世界上所有其他已知物体的尊重 宇宙将是无争议的。大脑是唯一的物体 能够理解宇宙甚至存在,或者为什么存在 是无穷多个素数,或者苹果因为 时空的弯曲,或者说遵从它自己天生的本能可以 道德上是错误的,或者它本身是存在的。它也不是独一无二的 局限于这种大脑活动的能力。冰冷的物理事实 它是唯一一种能把自己推进宇宙的物体 空间和背部没有伤害,或预测和防止流星撞击 它本身,或冷却到绝对温度以上十亿分之一度的物体 零,或者在银河系范围内探测其他同类

但我只想把它打印出来:

说明人脑在某些方面 远高于世界上所有其他已知物体的尊重 宇宙将是无争议的


感谢您的帮助

在该点上拆分文本;对于单个拆分,使用比使用限制更快:

text = soup.find_all('p')[0].get_text()
if len(text) > 100:
    text = text.partition('.')[0] + '.'
print(text)
如果只需要处理第一个
元素,请改用
soup.find()

text = soup.find('p').get_text()
if len(text) > 100:
    text = text.partition('.')[0] + '.'
print(text)
但是,对于给定的URL,示例文本显示为第二段:

>>> 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.'
汤。查找所有('p')[1] 如果说人脑的能力在某些方面远远优于宇宙中所有其他已知物体的能力,那将是无可争议的。大脑是唯一一种能够理解宇宙甚至在那里的物体,或者为什么有无限多的质数,或者苹果因为时空的弯曲而掉落,或者遵从它自己与生俱来的本能可能在道德上是错误的,或者它本身是存在的。它的独特能力也不局限于这种大脑活动。冰冷的物理事实是,它是唯一一种能够将自己推进太空并返回而不受伤害的物体,或者能够预测并阻止流星撞击自己,或者能够将物体冷却到绝对零度以上十亿分之一度,或者能够在银河系距离之外探测到其他同类物体的物体

>>>text=soup.find_all('p')[1]。get_text() >>>text.partition('.')[0]+'.' “说人脑在某些方面远远优于宇宙中所有其他已知物体的能力是无可争议的。”
在第一个
期间拆分
段落。参数
1
maxplit
进行分类,并节省不必要的额外拆分时间

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])
您可以使用
find('.')
,它返回您要查找的内容的第一次出现的索引

因此,如果段落存储在名为
paragration

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

显然这里缺少了控制部分,比如检查
段落
变量中包含的字符串是否有“.”等。。无论如何,find()返回-1,如果它没有找到要查找的子字符串。

在获得第一个paragraph(即第一个元素)后,可以将字符串拆分为字符串列表
mystring.split(sep='.')
。之后,您可以获得第一个列表元素。你能试试这个吗?我得到了该URL的不同输出,
'\n\n 2012年10月3日星期日07.00\xa0BST\n\n\n上一次修改是在2016年1月10日星期日09.11\xa0GMT\n\n'
。它是第二个
标记,用于保存该文本。这不必要地拆分了超出需要的部分。至少要限制拆分(第二个参数为
str.split()
),谢谢大家。这起作用了。但是,我不知道“[0]”在这行中的作用……任何人都可以解释?@skitel
str.partition()
返回一个包含三个元素(head、partition string和tail)的元组,但我们只对其中的第一个值感兴趣。我现在就知道了。非常感谢。
sentence_index = paragraph.find('.')
# add the '.'
sentence += 1
print(paragraph[0: sentence_index])