1.读取文本文件

读取与py文件同目录的txt文件,编码设定为encoding='utf-8'防止出现乱码,忽略读取中的错误errors='ignore',设定集合变量名paragraghs

with open('input.txt', 'r', encoding='utf-8',errors='ignore') as file:
    text = file. Read()

2.使用split()方法以回车(\n)为标识符,拆分段落

paragraphs = text. Split('\n')

3.创建变量html,并设定初始css设置

html = '<div style="text-align: left;font-size: 18px;line-height: 2;text-indent: 36px;">\n'

4.循环遍历集合,采用f-string,用大括号 {} 表示被替换字段,赋值给html变量

for paragraph in paragraphs:
    html += f'<p>{paragraph}</p>\n'

5.增加结束字段</div>

html += '</div>'

6.将集合html写入output.txt文件,同时编码设定为encoding='utf-8',并忽略错误errors='ignore'

with open('output.txt', 'w',encoding='utf-8',errors='ignore') as file:
    file. Write(html)

7.完整代码

with open('input.txt', 'r', encoding='utf-8',errors='ignore') as file:
    text = file. Read()
paragraphs = text. Split('\n')
html = '<div style="text-align: left;font-size: 18px;line-height: 2;text-indent: 36px;">\n'
for paragraph in paragraphs:
    html += f'<p>{paragraph}</p>\n'
html += '</div>'
with open('output.txt', 'w',encoding='utf-8',errors='ignore') as file:
    file. Write(html)

标签: none

评论已关闭