gpt4 book ai didi

python - 模式匹配并用 if else 循环替换字符串

转载 作者:太空狗 更新时间:2023-10-30 01:19:23 25 4
gpt4 key购买 nike

我有一个包含多行以“1ECLI H--- 12.345 .....”开头的文件。我想删除 I 和 H 之间的空格,并在迭代 H 模式时添加 R/S/T。例如。 H810 如果连续三行重复,则应添加字母 R、S(第二次迭代)、T(第三次迭代)。所以它会是H810R。任何帮助将不胜感激。
文字如下所示

1ECLI  H813   98   7.529   8.326   9.267
1ECLI H813 99 7.427 8.470 9.251
1ECLI C814 100 7.621 8.513 9.263
1ECLI H814 101 7.607 8.617 9.289
1ECLI H814 102 7.633 8.489 9.156
1ECLI H814 103 7.721 8.509 9.305
1ECLI C74 104 8.164 8.733 10.740
1ECLI H74R 105 8.247 8.690 10.799

根据变化

1ECLI H813R   98   7.529   8.326   9.267
1ECLI H813S 99 7.427 8.470 9.251
1ECLI C814 100 7.621 8.513 9.263
1ECLI H814R 101 7.607 8.617 9.289
1ECLI H814s 102 7.633 8.489 9.156
1ECLI H814T 103 7.721 8.509 9.305
1ECLI C74 104 8.164 8.733 10.740
1ECLI H74R 105 8.247 8.690 10.799

谢谢。

最佳答案

如果您的 Input_file 与显示的示例相同,那么您能否尝试按照 awk 进行操作,如果这对您有帮助,请告诉我。

awk '
BEGIN{
val[1]="R";
val[2]="S";
val[3]="T"
}
$2 !~ /^H[0-9]+/ || i==3{
i=""
}
$2 ~ /^H[0-9]+$/ && /^1ECLI/{
$2=$2val[++i]
}
1
' Input_file > temp_file && mv temp_file Input_file

也为答案添加解释如下。

awk '
BEGIN{ ##Starting BEGIN section of awk here.
val[1]="R"; ##creating an array named val whose index is 1 and value is string R.
val[2]="S"; ##creating array val 2nd element here whose value is S.
val[3]="T" ##creating array val 3rd element here whose value is T.
}
$2 !~ /^H[0-9]+/ || i==3{ ##Checking condition if 2nd field does not start from H and digits after that OR variable i value is equal to 3.
i="" ##Then nullifying the value of variable i here.
}
$2 ~ /^H[0-9]+$/ && /^1ECLI/{ ##Checking here if 2nd field value is starts from H till all digits till end AND line starts from 1ECLI string then do following.
$2=$2val[++i] ##re-creating value of 2nd field by adding value of array val whose index is increasing value of variable i.
}
1 ##Mentioning 1 here, which means it will print the current line.
' Input_file > temp_file && mv temp_file Input_file ##Mentioning Input_file name here.

关于python - 模式匹配并用 if else 循环替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47132438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com