簡體   English   中英

如何提取段落中的某個句子? Python

[英]How to extract a certain sentence in a paragraph? Python

我想從一個段落中提取某些句子,查看一組單詞Object C Statement: . 段落如下:

Object A 陳述:有一只貓,袋子里裝滿了肉。 那是一只戴着藍色帽子的紅貓。 Object B 聲明:有一只狗,袋子里裝滿了玩具。 那是一只戴着綠帽子的藍狗。 Object C 聲明:有一只海豚,袋子里裝滿了氣泡。 那是一只戴着橙色帽子的紫色海豚。 Object D 陳述:有一只斑馬,袋子里裝滿了草。 那是一匹戴着藍色帽子的白色斑馬。 Object E 聲明:有一只熊,袋子里裝滿了木頭。 那是一只戴着黑帽子的棕熊。

我要提取 Object C 語句:如下:

有一只海豚,袋子里裝滿了泡泡。 那是一只戴着橙色帽子的紫色海豚。

我遇到的所有示例都是拆分特定單詞等。

我試過這個,但它對我不起作用:

word="Object A Statement: There was a cat with a bag full of meat. It was a red cat with a blue hat. Object B Statement: There was a dog with a bag full of toys. It was a blue dog with a green hat. Object C Statement: There was a dolphin with a bag full of bubbles. It was a purple dolphin with an orange hat. Object D Statement: There was a zebra with a bag full of grass. It was a white zebra with a blue hat. Object E Statement: There was a bear with a bag full of wood. It was a brown bear with a black hat."
a, b, c, d, e = re.split(r"\B\s(?=[^\s:]+:)", word)
regex = re.compile(r"""Object A Statement\s(.*?)Object B Statement\s(.*?)Object C Statement\s(.*?)Object D Statement\s(.*?)Object E Statement\s(.*)""", re.S|re.X)
a, b, c, d, e = regex.match(word).groups()

您可以使用"\s*Object. Statement:\s*"拆分字符串

import re

word="Object A Statement: There was a cat with a bag full of meat. It was a red cat with a blue hat. Object B Statement: There was a dog with a bag full of toys. It was a blue dog with a green hat. Object C Statement: There was a dolphin with a bag full of bubbles. It was a purple dolphin with an orange hat. Object D Statement: There was a zebra with a bag full of grass. It was a white zebra with a blue hat. Object E Statement: There was a bear with a bag full of wood. It was a brown bear with a black hat."
result = re.split(r"\s*Object . Statement:\s*", word)
result = [r for r in result if len(r) > 0]
print("\n".join(result))

我得到以下結果。

There was a cat with a bag full of meat. It was a red cat with a blue hat.
There was a dog with a bag full of toys. It was a blue dog with a green hat.
There was a dolphin with a bag full of bubbles. It was a purple dolphin with an orange hat.
There was a zebra with a bag full of grass. It was a white zebra with a blue hat.
There was a bear with a bag full of wood. It was a brown bear with a black hat.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM