Python - 解析文本以换行符为分隔符,并为新行和段落添加html标签

2024-04-27 04:44:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在继承一个CSV文件,该文件以@@@作为行分隔符。我已经创建了一些Python代码,可以在@@处拆分,并将文本分隔成单独的行。我的问题是,原始文本的格式是段落和新行,但我的代码以某种方式将所有内容聚集在一起。这将进入MS访问表单,供人们查看医疗记录。这将是理想的主要原始格式。因为我认为这是不可能的,所以我希望我可以为新行添加一个“br”html标记,为段落添加一个“p”html标记。我的问题是,我不知道如何让Python进行新行或段落拆分

我的输出如下(不理想):

ID |报告文本

1 |糖尿病(DM),俗称糖尿病,是一种 以高血糖水平为特征的一组代谢紊乱 在很长一段时间内。糖尿病要么是由于胰腺,要么不是 产生足够的胰岛素,或者身体细胞没有反应 适当的胰岛素产生。糖尿病主要有三种类型 糖尿病:-1型糖尿病是由于胰腺不能产生 由于β细胞的丢失,需要足够的胰岛素。这张表格以前是 被称为“胰岛素依赖型糖尿病”(IDDM)或“青少年糖尿病” 糖尿病”。原因不明2型糖尿病始于胰岛素 抵抗,细胞对胰岛素没有反应的状态 对。随着疾病的进展,胰岛素的缺乏也可能发展

2 |妊娠期糖尿病是第三种主要形式,在怀孕时发生 既往无糖尿病病史的女性会出现高血糖 水平。不要患糖尿病,你会好起来的

(请参阅短语引用代码)我希望能够添加html标记,以便我的富文本MS Access表单能够保持换行符和段落格式。例如,在第一段中,我希望在“延长期限”之后加上“p”标记。在第三段中,在“原因未知”之后加上“br”标记。提前谢谢

t = '@@@ Diabetes mellitus (DM), commonly known as diabetes, is a 
group of metabolic disorders characterized by high blood sugar levels 
over a prolonged period.  

Diabetes is due to either the pancreas not producing enough insulin,
or the cells of the body not responding properly to the insulin produced.
There are three main types of diabetes mellitus:

- Type 1 DM results from the pancreas' failure to produce enough insulin 
due to loss of beta cells. This form was previously referred to 
as "insulin-dependent diabetes mellitus" (IDDM) or "juvenile 
diabetes".The cause is unknown.
- Type 2 DM begins with insulin resistance, a condition in which cells 
fail to respond to insulin properly. As the disease progresses, a lack of 
insulin may also develop. 

@@@ Gestational diabetes is the third main form, and occurs when pregnant 
women without a previous history of diabetes develop high blood sugar 
levels. 

Do not get diabetes and you will be okay!'

data = list(enumerate( (x.strip() for x in t.split("@@@") if x.strip()),
1))

print(data)
print("")

import csv
with open("t.txt", "w", newline = "") as csvfile:
   writer = csv.writer(csvfile, delimiter='|')
   writer.writerow(('ID', 'Reporttext'))
   writer.writerows(data)

print( open("t.csv").read())

Tags: oftheto代码标记文本is格式