python - 根据关键字对文本进行分类
问题描述
我有类似以下格式的文档,我想用 python 对其进行分类,例如
Outline:
1. Lorem Ipsum
2. Lorem Ipsum
Preface:
This is sample generated words of the documents
那些必须分类为数组,例如
[Outline: 1. Lorem Ipsum 2. Lorem Ipsum, Preface: This is sample generated words of the documents ]
或存储在不同的变量中,例如
outline = segment_by_word("outline")
preface = segment_by_word("preface")
print(preface ) #This is sample generated words of the documents
解决方案
我假设只有两个类别Ouline
和Preface
. 下面的代码将行作为元组添加到列表中,其中行 # 然后是行信息
lines_by_category = {'Outline': [], 'Preface': []}
category = None
count = 0
for line in lines: # Assuming you know how to get to the point of reading lines
if line.find(r'Outline:'):
category = 'Outline'
elif line.find(r'Preface:'):
category = 'Preface'
category_list = lines_by_category[category]
category_list.append((count, line)) # Updates the original list because it is pointing to the same one
推荐阅读
- node.js - Nodemon中的神秘参数-r
- python - TypeError: wrapper() 接受 1 个位置参数,但给出了 2 个
- elasticsearch - 使用输入数组进行 Elasticsearch 过滤,其中
- c - 如何将 2 个大数字乘以字符串(使用之前添加 2 个字符串的函数)?C
- http - Flutter http请求上传mp3文件
- java - Android Studio 布局没有响应
- c++ - 使用 IMFSinkWriter 编码的视频的播放速度根据宽度变化
- java - 切换到新的 Google Maps SDK 时出现迁移错误
- javascript - 考虑到 Windows 10 全局缩放的鼠标位置
- python - 连接两行或多行,而不会在最后一行出现重复