2024-05-10 12:12:42 发布
网友
我想知道如何转换类似以下内容的文本:
Chapter 3 Convex Functions 97 3.1 Definitions 98 3.2 Basic Properties 103
收件人:
通过使用一些方便但功能强大的文本操作语言和/或实用程序,如sed、awk、regex、perl、python。。。在
谢谢和问候!在
注: 在每一行中,最后一个数字重复。在
下面是一个Perl解决方案:
while (<DATA>) { s/^(.+ (\d+))$/("$1" "#$2")/; print; } __DATA__ Chapter 3 Convex Functions 97 3.1 Definitions 98 3.2 Basic Properties 103
印刷品:
或者作为一条直线:
perl -pe 's/^(.+ (\d+))$/("$1" "#$2")/'
在Python中
"Chapter 3 Convex Functions 97".rsplit(None,1)
给予
处理一个文本块
txt = """Chapter 3 Convex Functions 97 3.1 Definitions 98 3.2 Basic Properties 103""" for line in txt.split('\n'): line = line.strip().rsplit(None,1) print('("{0} {1}" "#{1}")'.format(*line))
("Chapter 3 Convex Functions 97" "#97") ("3.1 Definitions 98" "#98") ("3.2 Basic Properties 103" "#103")
编辑:我已经根据您的注释更新了它,以便页码重复。在
几乎所有版本的python都可以使用
infile = open("input.txt") outfile = open("output.txt", "w") for line in infile: line, last = line.rstrip().rsplit(" ", 1) outfile.write('("%s %s" "#%s")\n' % (line, last, last))
下面是一个Perl解决方案:
印刷品:
^{pr2}$或者作为一条直线:
在Python中
给予
^{pr2}$处理一个文本块
给予
编辑:我已经根据您的注释更新了它,以便页码重复。在
几乎所有版本的python都可以使用
相关问题 更多 >
编程相关推荐