开发者

python string replace unknown number

开发者 https://www.devze.com 2023-04-11 07:46 出处:网络
I am a beginner with PYTHON and useless with regex and are struggling to replace an unknown number in a file with a new number. I have looked through the python how tos and examples for re but still c

I am a beginner with PYTHON and useless with regex and are struggling to replace an unknown number in a file with a new number. I have looked through the python how tos and examples for re but still can't make any progress on how to create the expression.

# myfile.txt
Some text
More text
Option  "BlankTime" "15"
more text

I want to replace "15" with another number, this line only appears once in the file, but the line number it is on is unknown, and the value of 15 is also unknown and could b开发者_JAVA技巧e any number contained in the quotation marks.

Best way would be to do it with python ( re ?? ) but if that can't be done then maybe sed ??


It sounds like you're looking for a particular parameter (BlankTime). This can be done with the following sed one-liner:

cat myfile.txt | sed 's/\("BlankTime"\s*"\)[^"]*/\1987/'

This'll search for "BlankTime" and replace its value with 987, leaving all the other lines intact.

edit To replace the contents of the file, use the following two-step approach:

cat myfile.txt | sed 's/\("BlankTime"\s*"\)[^"]*/\1987/' > myfile.txt.tmp
mv myfile.txt.tmp myfile.txt


import re
with open("myfile.txt", "r") as myfile:
    mytext = myfile.read()
pattern = re.compile(r'^(Option\s+"BlankTime"\s+")(\d+)"', re.MULTILINE)
mystr = pattern.sub(r'\1REPLACED"', mytext)
with open("myfile.txt", "w") as myfile:
    myfile.write(mytext)

This will replace all occurrences in the file at once. I've put the number into capturing parentheses in case you'd want to do something with it before the replacement.


myfile = open('myfile.txt', 'r')
text = myfile.read()
myfile.close()

print re.sub(r'\d+', '42', text)

\d matches a number, + matches at least one occurrence of the preceding pattern.

0

精彩评论

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