首页 > 解决方案 > 使用python根据文本中的主题提取子文本(数据清洗/提取/处理)

问题描述

考虑文本1:

什么是 Lorem Ipsum:
Lorem Ipsum 只是印刷和排版行业的虚拟文本。

它来自哪里:
与流行的看法相反,Lorem Ipsum 不仅仅是随机文本。

我们为什么要使用它:
一个由来已久的事实是,读者在查看页面布局时会被页面的可读内容分散注意力。

文本2:

什么是 Lorem Ipsum:
Lorem Ipsum 只是印刷和排版行业的虚拟文本。

其他主题:
Lorem Ipsum 的段落有很多变体。

我们为什么要使用它:
一个由来已久的事实是,读者在查看页面布局时会被页面的可读内容分散注意力。

文本3:

什么是 Lorem Ipsum:
Lorem Ipsum 只是印刷和排版行业的虚拟文本。

它来自哪里:
与流行的看法相反,Lorem Ipsum 不仅仅是随机文本。

其他一些主题:
多年来,各种版本已经演变。

我可以使用 python 处理此文本以在开始和结束字符串之间进行提取。我使用的代码 -

# This code is run once separately for each text variation 
import sys
s = "text1 or text2 or text3" # one at a time
start_String = s.find("What is Lorem Ipsum:")
end_String = s.find("Why do we use it:")
if start_String == -1 or end_String == -1:
    print("Not found")
    sys.exit(0)
print(s[start_String:end_String])

但我的要求是不同的。我只需要与“什么是 Lorem Ipsum:”、“它来自哪里:”、“我们为什么使用它:”相关的文本。

预期结果:
text1:

什么是 Lorem Ipsum:
Lorem Ipsum 只是印刷和排版行业的虚拟文本。

它来自哪里:
与流行的看法相反,Lorem Ipsum 不仅仅是随机文本。

我们为什么要使用它:
一个由来已久的事实是,读者在查看页面布局时会被页面的可读内容分散注意力。

文本2:

什么是 Lorem Ipsum:
Lorem Ipsum 只是印刷和排版行业的虚拟文本。

我们为什么要使用它:
一个由来已久的事实是,读者在查看页面布局时会被页面的可读内容分散注意力。

文本3:

什么是 Lorem Ipsum:
Lorem Ipsum 只是印刷和排版行业的虚拟文本。

它来自哪里:
与流行的看法相反,Lorem Ipsum 不仅仅是随机文本。

我在一个巨大的数据集中有像上面这样的文本集合。我需要做的就是根据必要的主题仅提取所需的子文本。我怎样才能在python中实现这个?我希望我说得通。

标签: pythontextnlpdata-cleaning

解决方案


这正是您想要的:

my_list=["""What is Lorem Ipsum:
Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Where does it come from:
Contrary to popular belief, Lorem Ipsum is not simply random text.

Why do we use it:
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.""","""What is Lorem Ipsum:
Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Why do we use it:
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.""","""What is Lorem Ipsum:
Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Where does it come from:
Contrary to popular belief, Lorem Ipsum is not simply random text."""]


new_list =[]   ## Creating an empty list

for i in range(len(my_list)):
    new_list.extend(my_list[i].split(":"))

推荐阅读