我正在尝试从文档标题列表中快速创建DITA keydef列表。 如果标题是“设备用户指南”,我想创建一个这样的keydef:
<keydef keys="Device_User_Guide" class="+ map/topicref mapgroup-d/keydef ">
<topicmeta class="- map/topicmeta ">
<keywords class"- topic/keywords ">
<keyword class="- topic/keyword ">Device User Guide</keyword>
</keywords>
</topicmeta>
</keydef>
标题是从titles.txt文件中提取的,其中每个都是新行。这导致键(Device_User_Guide)在末尾包含\ n,所以我的输出是这样的:
<keydef keys="Device_User_Guide
" class="+ map/topicref mapgroup-d/keydef ">
<topicmeta class="- map/topicmeta ">
<keywords class"- topic/keywords ">
<keyword class="- topic/keyword ">Device User Guide</keyword>
</keywords>
</topicmeta>
</keydef>
我设法用下划线替换空格并使用rstrip作为关键字,但是如何在我执行替换操作的同时剥离换行符?这是我的代码:
title = open('titles.txt', 'r')
keydefs = open('keydefs.txt', 'w')
for line in title:
keydefs.write('<keydef keys="%s" class="+ map/topicref mapgroup-d/keydef ">\n <topicmeta class="- map/topicmeta ">\n <keywords class"- topic/keywords ">\n <keyword class="- topic/keyword ">%s</keyword>\n </keywords>\n </topicmeta>\n</keydef>' % (line.replace(" ","_"), line.rstrip()))
答案 0 :(得分:0)
我明白了。只需将line.rstrip()
移动到循环的开头。
title = open('titles.txt', 'r')
keydefs = open('keydefs.txt', 'w')
for line in title:
newline = line.rstrip()
keydefs.write('<keydef keys="%s" class="+ map/topicref mapgroup-d/keydef ">\n <topicmeta class="- map/topicmeta ">\n <keywords class"- topic/keywords ">\n <keyword class="- topic/keyword ">%s</keyword>\n </keywords>\n </topicmeta>\n</keydef>' % (newline.replace(" ","_"), newline))