Reputation: 1
My data:
1 255 59 0 1 255 0 1 1 0 4 0 5
0 1 255 1 253 0 90 1 1 0 2 0 233
I'm new to python and I need to replace all value in text file by use conditions:
If value in line = 255, Replace as 1
If value in line < 255 (254, 253, 252...), Replace as 0
So, My target data is:
1 1 0 0 1 1 0 1 1 0 0 0 0
0 1 1 1 0 0 0 1 1 0 0 0 0
How can I solve this problem?
Actually, I tried to fix it but doesn't work with my data.
This is my code:
f1 = open('20130103.txt','r')
f2 = open('20130103_2.txt','w')
count = 255
for line in f1:
line = line.replace('255','1')
count = count-1
line = line.replace('%d'%(count), '0')
f2.write(line)
f1.close()
f2.close()
And result is:
1 1 59 0 1 1 0 1 1 0 4 0 5
0 1 1 1 0 0 90 1 1 0 2 0 233
Upvotes: 0
Views: 359
Reputation: 63777
The eye catcher here is the number 255
, for which you would want to display 1
, which clearly indicates, you are only interested in the 8th bi
t.
The only case which looks strange is how your o/p not conforming with your requirement, does not manipulate 1
in which case, you have to leave it out of your transformation
If I have to trust your requirement
>>> with open("test.in") as fin, open("test.out","w") as fout:
for line in fin:
line = (e >> 7 for e in map(int, line.split()))
fout.write(''.join(map(str, line)))
fout.write('\n')
If I have to trust your data
>>> with open("test.in") as fin, open("test.out","w") as fout:
for line in fin:
line = (e >> 7 if e != 1 else 1 for e in map(int, line.split()))
fout.write(''.join(map(str, line)))
fout.write('\n')
Another alternate view to this problem.
>>> with open("test.in") as fin, open("test.out","w") as fout:
for line in fin:
line = (e / 255 if e != 1 else 1 for e in map(int, line.split()))
fout.write(''.join(map(str, line)))
fout.write('\n')
Upvotes: 2
Reputation: 298552
You could do something like this:
with open('20130103.txt', 'r') as f1, open('20130103_2.txt', 'w') as f2:
for line in f1:
values = line.split()
new_values = ' '.join('1' if value == '255' else '0' for value in values)
f2.write(new_values + '\n')
line.split()
splits the line into chunks. 'a b'.split() == ['a', 'b']
'1' if value == '255' else '0' for value in values
is a generator that just outputs '1'
or '0'
, depending on the value of an item in your list of values.' '.join()
joins together the values in the list (or generator, in this case) with a space.Upvotes: 1
Reputation: 4852
Here's an example of how you can pass re.sub
a function -- instead of a replace string -- to gain really fine control over how replacements are done:
import re
lines = ['1 255 59 0 1 255 0 1 1 0 4 0 5',
'0 1 255 1 253 0 90 1 1 0 2 0 233']
def do_replace(match):
number = int(match.group(0))
if number == 0 or number == 1:
return str(number)
elif number == 255:
return '1'
elif number < 255:
return '0'
else:
raise ValueError
for line in lines:
print re.sub(r'\d+', do_replace, line)
prints:
1 1 0 0 1 1 0 1 1 0 0 0 0
0 1 1 1 0 0 0 1 1 0 0 0 0
Upvotes: 1