2 回答
![?](http://img1.sycdn.imooc.com/545861f00001be3402200220-100-100.jpg)
TA贡献1817条经验 获得超14个赞
如果类别、项目和描述由双换行符分隔,您可以使用此示例来解析它(regex101):
import re
txt = '''1. Food : Cake : Baked sweet food made from flour, sugar and other ingredients.
2. Electronics : Computer : A machine to carry out a computer programming operation.
Computers mainly consists of a CPU, monitor, keyboard and a mouse.
3. Automobile : Car : Car is a four wheeled motor vehicle used for transportation.'''
for cat, item, desc in re.findall(r'^(?:\d+)\.([^:]+):([^:]+):(.*?)(?:\n\n|\Z)', txt, flags=re.M|re.S):
print(cat)
print(item)
print(desc)
print('-' * 80)
印刷:
Food
Cake
Baked sweet food made from flour, sugar and other ingredients.
--------------------------------------------------------------------------------
Electronics
Computer
A machine to carry out a computer programming operation.
Computers mainly consists of a CPU, monitor, keyboard and a mouse.
--------------------------------------------------------------------------------
Automobile
Car
Car is a four wheeled motor vehicle used for transportation.
--------------------------------------------------------------------------------
![?](http://img1.sycdn.imooc.com/5458683f00017bab02200220-100-100.jpg)
TA贡献2019条经验 获得超9个赞
这可能是一种基本方法,但它适用于您提供的示例输入:
[0-9]+\s*.\s*(\w*)\s*:\s*(\w*)\s*:\s*((?:.*[\n\r]?)+?)(?=$|\d\s*\.)
基本上,我们在描述中采用尽可能多的文本(包括换行符),直到到达文件末尾或另一个数字索引。
添加回答
举报