如何将每个lin末尾附近的数字相加

2024-04-29 08:03:46 发布

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

假设文件中有一些文本:

(bookmarks
("Chapter 1 Introduction 1" "#1"
("1.1 Problem Statement and Basic Definitions 2" "#2")
("1.2 Illustrative Examples 4" "#4")
("1.3 Guidelines for Model Construction 26" "#26")
("Exercises 30" "#30")
("Notes and References 34" "#34"))
)

如果每行最后一个数字有一个,我怎么加11

^{pr2}$

通过使用sed、awk、python、perl、regex。。。。在

谢谢和问候!在


Tags: and文件文本formodelbasicexamplesstatement
3条回答

在Python中,请尝试:

import re
m = re.search(r'(?<=#)([0-9]+)',txt)

找到下一个号码。然后设置:

^{pr2}$

只要search找不到任何进一步的匹配项,就重复该操作(例如在while循环中)。在

注意:regExp(?<=#)([0-9]+)匹配#-字符后面的任何数字序列。start()生成下一个匹配的开始位置;end()生成结束位置,group()生成实际匹配。表达式str(int(m.group()) +11)将匹配的数字转换为int值,加11并重新转换为字符串。在

awk -F'#' 'NF>1{split($2,a,"[0-9]+");print $1 FS $2+11 a[2];next}1' infile

概念证明

^{pr2}$
use strict;
use warnings;
while(my $line = <DATA>){
  $line =~ s/#(\d+)/'#'.($1 + 11)/e;
}
__DATA__
(bookmarks
("Chapter 1 Introduction 1" "#1"
("1.1 Problem Statement and Basic Definitions 2" "#2")
("1.2 Illustrative Examples 4" "#4")
("1.3 Guidelines for Model Construction 26" "#26")
("Exercises 30" "#30")
("Notes and References 34" "#34"))
)

输出:

^{pr2}$

相关问题 更多 >