Am new to python and I am trying to scan through a file and convert any integer I find to a value of 1. Is there a regex I could use ? or some kind of function which I could use
Asked
Active
Viewed 56 times
-3
-
1`perl -pi -e 's/\d++/1/g' myfile.txt`. Why complicate matters? – Boris the Spider Oct 17 '15 at 17:19
2 Answers
1
def numbers_with_zero(file_):
import re
# Note:current regex will convert floats and ints to 0
# if one wants to just convert ints, and convert them to 1
# do line = re.sub(r'[-+]?\d+',r'1',line)
file_contents = []
# read file, change lines
with open(file_, 'r') as f:
for line in f:
# this regex should take care of ints, floats, and sings, if any
line = re.sub(r'[-+]?\d*\.\d+|\d+',r'0',line)
file_contents.append(line)
# reopen file and write changed lines back
with open(file_, 'w') as f:
for line in file_contents:
f.write(line)

LetzerWille
- 5,355
- 4
- 23
- 26
-
be careful, he wants to convert each integer to 1, it means no doubles and r'1', not r'0' in re.sub function. – ilyakhov Oct 17 '15 at 17:41
-
@Gregg heading says: Converting all integers in a file to zero. I ll'comment the function, so that users will have a choice.. thanks for you remark – LetzerWille Oct 17 '15 at 17:45
0
Olle Muronde, you can find information about how to rewrite lines in file in the post. Each line of file could be considered as a string, the simplest way to replace some symbols by others is re.sub
function from re
module. I strongly recommend you to learn python documentation and to use google or stackoverflow search more often, because plenty good answers have been posted already.