开发者

Newbie python - replace in an array

开发者 https://www.devze.com 2023-03-02 14:18 出处:网络
In a file, I have the following lines NetConn_msa[0].time=0.0 NetConn_msa[1].time=0.0 etc for 60 elements.

In a file, I have the following lines

NetConn_msa[0].time=0.0

NetConn_msa[1].time=0.0 etc for 60 elements. 

I need to write a script to change the time from 0.0 to 0.5.

I started with st.replace("delay=0.0","delay=0.05") and then tried to find the string to replace

开发者_如何学运维sub=re.compile("\[\d+\]\.\w+=[0]\.[0]")
result=sub.search(st)

Can someone please help me since I am very new to programming. Thanks!


Why not do this the really easy way: manually edit the file so that the offending 60 lines are replaced by:

for x in range(60):
    NetConn_msa[x].time = 0.5


Script:

import re

x = """NetConn_msa[0].time=0.0
NetConn_msa[59].time=0.0
NetConn_msa[0].time=9.9
NetConn_msa[60].time=0.0
NetConn_msa[61].time=0.0
NetConn_msa[99].time=0.0
NetConn_msa[100].time=0.0
NetConn_msa[0].other=0.0
NetConn_msa[0].time=0.01
PseudoNetConn_msa[59].time=0.0
Foo[0].bar=0.0"""

print "=== not strict enough ==="
print re.sub("(\]\.\w+)=0.0","\\1=0.5",x)

print "=== stricter ==="
print re.sub(r"(NetConn_msa\[[1-5]?\d\]\.time)=0.0\b", r"\1=0.5", x)

Output:

=== not strict enough ===
NetConn_msa[0].time=0.5
NetConn_msa[59].time=0.5
NetConn_msa[0].time=9.9
NetConn_msa[60].time=0.5
NetConn_msa[61].time=0.5
NetConn_msa[99].time=0.5
NetConn_msa[100].time=0.5
NetConn_msa[0].other=0.5
NetConn_msa[0].time=0.51
PseudoNetConn_msa[59].time=0.5
Foo[0].bar=0.5
=== stricter ===
NetConn_msa[0].time=0.5
NetConn_msa[59].time=0.5
NetConn_msa[0].time=9.9
NetConn_msa[60].time=0.0
NetConn_msa[61].time=0.0
NetConn_msa[99].time=0.0
NetConn_msa[100].time=0.0
NetConn_msa[0].other=0.0
NetConn_msa[0].time=0.01
PseudoNetConn_msa[59].time=0.0
Foo[0].bar=0.0


x = """NetConn_msa[0].time=0.0

NetConn_msa[1].time=0.0 etc for 60 elements. """

print re.sub("(\]\.\w+)=0.0","\\1=0.5",x)

#NetConn_msa[0].time=0.5

#NetConn_msa[1].time=0.5 etc for 60 elements. 


Why not do this the easy way?

st.replace('.time=0.0\n','.time=0.5\n')

0

精彩评论

暂无评论...
验证码 换一张
取 消