当前位置: 代码迷 >> 综合 >> python实现 CCF201703-3 Markdown
  详细解决方案

python实现 CCF201703-3 Markdown

热度:89   发布时间:2023-10-23 04:37:34.0

题目链接:https://blog.csdn.net/qq_34950042/article/details/88427915

满分代码

import sysdata = []           # 记录Markdown转化为html后的文档,data中的一个元素代表html的一行(除开'')
flag = False        # 标记段落是否多行
list_tag = False    # 标记无序列表是否多行
for line in sys.stdin: # line代表键盘输入的每行内容# 区块line = line.strip()if '#' in line:                          # 标题count = line.count("#")              # 计算是第几标题temp = line.split('#')[-1].strip()   # 这里分割最好不要用“空格”防止标题含有空格temp = "<h" + str(count) + ">" + temp + "</h" + str(count) + ">"elif '*' in line:                        # 无序列表if list_tag == False:data.append('<ul>')list_tag = Truetemp = line.split("*")[-1].strip()   # 采用“*”分割temp = "<li>" + temp + "</li>"else:                                    # 段落if line and flag == False:           # 首次出现段落temp = '<p>' + lineflag = Trueelif line and flag == True:          # 中间出现段落temp = lineelif line == '' and flag == True:    # 段落结束,修改data最后一个元素的值(即加上'</p>')data[-1] = data[-1] + '</p>'flag = Falsetemp = ''elif line == '' and list_tag == True:# 无序列表结束data.append("</ul>")temp = ""list_tag = Falseelse:temp = ''flag = Falselist_tag = False# 行内# 强调i = 1                                   # 标记是第一个"_",还是第二个while '_' in temp:                      # 注意强调以及超链接都可能多个,所以用无限循环index_1 = temp.find('_')if i == 1:temp = temp[:index_1] + '<em>' + temp[index_1 + 1:]i = 2else:temp = temp[:index_1] + '</em>' + temp[index_1 + 1:]i = 1# 超链接while '[' in temp:                      # 注意这里是while,可能有多个超链接i1 = temp.find('[')i2 = temp.find(']', i1 + 1)i3 = temp.find('(', i2 + 1)i4 = temp.find(')', i3 + 1)temp = temp[:i1] + '<a href="' + temp[(i3 + 1):i4] + '">' + temp[(i1 + 1):i2] + "</a>" + temp[(i4 + 1):]data.append(temp)                       # 将转化后的html加入data
if flag == True:                            # 当以段落结束时data[-1] = data[-1] + '</p>'
if list_tag == True:                        # 当以无序列表结束时data.append("</ul>")
for d in data:if d == '':continueprint(d)