gpt4 book ai didi

python - 从文件中提取每一行并将其作为变量传递给 "foreach"循环

转载 作者:太空狗 更新时间:2023-10-29 12:07:19 24 4
gpt4 key购买 nike

有人可以帮我找出使用任何脚本执行此操作的简单方法吗?我将在 Linux 上运行脚本

1 ) 我有一个文件 1,其中包含以下几行:

 (Bank8GntR[3] | Bank8GntR[2] | Bank8GntR[1] | Bank8GntR[0] ),

(Bank7GntR[3] | Bank7GntR[2] | Bank7GntR[1] | Bank7GntR[0] ),

(Bank6GntR[3] | Bank6GntR[2] | Bank6GntR[1] | Bank6GntR[0] ),

(Bank5GntR[3] | Bank5GntR[2] | Bank5GntR[1] | Bank5GntR[0] ),

2 ) 我需要将 file1 的内容修改如下并写入 file2

 (Bank15GntR[3] | Bank15GntR[2] | Bank15GntR[1] | Bank15GntR[0] ),

(Bank14GntR[3] | Bank14GntR[2] | Bank14GntR[1] | Bank14GntR[0] ),

(Bank13GntR[3] | Bank13GntR[2] | Bank13GntR[1] | Bank13GntR[0] ),

(Bank12GntR[3] | Bank12GntR[2] | Bank12GntR[1] | Bank12GntR[0] ),

所以我必须:

  1. 从文件中读取每一行1,
  2. 使用正则表达式“搜索”,
  3. 匹配 Bank[0-9]GntR,
  4. 用“7 added to number matched”替换\1,
  5. 将它插回行中,
  6. 将该行写入一个新文件。

最佳答案

在 Python 中做这样的事情怎么样:

# a function that adds 7 to a matched group.
# groups 1 and 2, we grabbed (Bank) to avoid catching the digits in brackets.
def plus7(matchobj):
return '%s%d' % (matchobj.group(1), int(matchobj.group(2)) + 7)

# iterate over the input file, have access to the output file.
with open('in.txt') as fhi, open('out.txt', 'w') as fho:
for line in fhi:
fho.write(re.sub('(Bank)(\d+)', plus7, line))

关于python - 从文件中提取每一行并将其作为变量传递给 "foreach"循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6270155/

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