python读取不规则txt字段
时间: 2023-10-02 14:10:11 浏览: 232
可以使用Python的正则表达式模块re来读取不规则的txt字段。具体操作方式是,先读取整个txt文件,然后使用正则表达式来匹配需要提取的字段,最后将匹配到的内容进行处理和输出。下面是一个示例代码:
```
import re
# 读取txt文件
with open('example.txt', 'r') as file:
txt = file.read()
# 使用正则表达式来匹配需要提取的字段
pattern = r'\d+\.[\w\s]+:\s(.+?)(?=\d+\.[\w\s]+:|\Z)'
fields = re.findall(pattern, txt, re.DOTALL)
# 输出提取的字段
for field in fields:
print(field.strip())
```
这段代码可以提取类似这样的字段:
```
1. Field One: This is the content of field one.
2. Field Two:
This is the content of field two.
It can span multiple lines.
3. Field Three: This is the content of field three.
```
输出结果为:
```
This is the content of field one.
This is the content of field two.\nIt can span multiple lines.
This is the content of field three.
```
阅读全文