python-3.x - 如何搜索特定字符串并替换此字符串usign python中的数字?
问题描述
我有一个 Fortran 代码的文本文件。我正在尝试创建此代码的副本(Fortran 文件)。但是在我创建的每个副本中,我都想找到并替换一些东西。举个例子:
这是代码,我想搜索 pMax、tShot,并替换它旁边的数字。
如果有人能给我一个关于如何使用 python 3.x 来完成的提示,我将不胜感激。谢谢你。
这是我的尝试:
没有错误,但由于某种原因,re.sub() 不会将字符串替换为目标文件中所需的字符串“pMax”。尽管打印 re.sub 的返回值表明 pMax 已修改为所需的值。
vd_load_name = []
for i in range(len(Pressure_values)):
vd_load_name.append('{}_{}MPa'.format(n,int(Pressure_values[i])))
src_dir = os.getcwd() #get the current working dir
# create a dir where we want to copy and rename
dest_dir = os.mkdir('vd_loads')
os.listdir()
dest_dir = src_dir+"/vd_loads"
for i in range(len(vd_load_name)):
src_file = os.path.join(src_dir, 'n_t05_pressure_MPa.txt')
shutil.copy(src_file,dest_dir) #copy the file to destination dir
dst_file = os.path.join(dest_dir,'n_t05_pressure_MPa.txt')
new_dst_file_name = os.path.join(dest_dir, vd_load_name[i]+'.txt')
os.rename(dst_file, new_dst_file_name)#rename
os.chdir(dest_dir)
dest_file_path = dest_dir+'/'+vd_load_name[i]+'.txt'
with open(dest_file_path,'r+') as reader:
#reading all the lines in the file one by one
for line in reader:
re.sub(r"pMax=\d+", "pMax=" + str(int(Pressure_values[i])), line)
print(re.sub(r"pMax=\d+", "pMax=" + str(int(Pressure_values[i])), line))
实际上,我要编辑的 fortran 代码的一部分:
integer :: i !shot index in x
integer :: j !shot index in y
integer :: sigma !1D overlap
dimension curCoords(nblock,ndim), velocity(nblock,ndim),dirCos(nblock,ndim,ndim), value(nblock)
character*80 sname
pMax=3900d0 !pressure maximum [MPa] Needs to be updated!!
fact=1d0 !correction factor
JLTYP=0 !key that identifies the distributed load type, 0 for Surface-based load
t=stepTime !current time[s]
tShot=1.2d-7 !Time of a shot[s] Needs to be updated!!
sigma=0 !1D overlap in x&y [%]
解决方案
推荐阅读
- python - 如何在 Python 中获取 CSV 奇偶行?
- python - python:assert_has_calls 在循环中取最后一个值
- java - 将一列拆分为多列
- python - pip3.6 install mysqlclient==1.3.12 失败并出现错误:未知类型名称“my_bool”;你的意思是'布尔
- html - CSS中如何防止翻转卡重叠导航栏
- c# - 使用 CANoe 和 C# 接收 UDP 消息
- java - 在 try/catch 之外找不到变量
- ios - Firebase 时间戳解码
- php - 在 GAE php74 标准环境中将 PHP 错误与 HTTP 请求相关联
- python - 熊猫有条件地插入空行和块