windows系统中python读取文件1.txt 提取出文件中指定字段生成word表格
时间: 2023-06-24 13:07:37 浏览: 191
可以使用Python的`docx`库来生成Word表格,使用`re`库来匹配文件中的字段。具体实现步骤如下:
1. 安装`python-docx`库和`re`库:在命令行窗口输入以下命令:
```
pip install python-docx
pip install re
```
2. 导入需要的库:
```python
import docx
import re
```
3. 打开文件并读取内容:
```python
with open('1.txt', 'r', encoding='utf-8') as f:
content = f.read()
```
4. 使用正则表达式匹配需要提取的字段,例如匹配姓名和年龄:
```python
name_pattern = r'姓名:(\w+)'
age_pattern = r'年龄:(\d+)'
name = re.search(name_pattern, content).group(1)
age = re.search(age_pattern, content).group(1)
```
5. 创建Word文档并添加表格:
```python
doc = docx.Document()
table = doc.add_table(rows=2, cols=2)
table.cell(0, 0).text = '姓名'
table.cell(0, 1).text = '年龄'
table.cell(1, 0).text = name
table.cell(1, 1).text = age
```
6. 保存Word文档:
```python
doc.save('output.docx')
```
完整代码如下:
```python
import docx
import re
with open('1.txt', 'r', encoding='utf-8') as f:
content = f.read()
name_pattern = r'姓名:(\w+)'
age_pattern = r'年龄:(\d+)'
name = re.search(name_pattern, content).group(1)
age = re.search(age_pattern, content).group(1)
doc = docx.Document()
table = doc.add_table(rows=2, cols=2)
table.cell(0, 0).text = '姓名'
table.cell(0, 1).text = '年龄'
table.cell(1, 0).text = name
table.cell(1, 1).text = age
doc.save('output.docx')
```
阅读全文