开发者

text replace in python

I have had written text file in which I have statements like these :

WriteByte(0x6000, 0x28);    // Register Value ...    

WriteByte(0x6002, 0x02);    //      

WriteByte(0x6004, 0x08);    //      

I ha开发者_如何学运维ve to replace 0x28 with a user given value as an input

This means I have replace 0x28 with usr_value which may be 0x35 or 0x38 etc..

Also I also cant count on there being only 0x28 it coould be any other value whose contents are to be replaced by user given content.

Also since the text file is hand written it could have extra spaces or not

WriteByte(0x6000,0x28); // Register Value ...

or

WriteByte( 0x6000 , 0x28);  // Register Value ...

I tried using string.replace but it may not work for all combinations. What's the best way of doing this apart from using Regular expressions ?


From the discussion below, if you want to find all the second arguments to WriteBytes and prompt for replacing, you can do something like this:

  1. parse the file to find all the 2nd arguments to WriteBytes, using a regular expression, and store them in a set (which will handle duplicates for you)

  2. for all the values you've seen, prompt the user for the replacement value, and store that in a dictionary

  3. read the file again, and perform the replacements, storing the modified lines in a list, together with the unmodified lines

  4. write the data back to disk.

Sample code:

import re

filename = '/tmp/toto.txt'

write_byte_re= r'WriteByte\([^,]+,\s*([^\)]+)\)'

# look for all potential substitutions
search_values = set()
f = open(filename)
for line in f:
    print line
    match_object = re.match(write_byte_re, line)
    if match_object is None: # nothing found, keep looking
        continue
    else:
        search_values.add(match_object.group(1)) # record the value

f.seek(0) # rewind file

substitutions = {}
for value in search_values:
    print "What do you want to replace '%s' with? (press return to keep as is)"
    new_value = raw_input('> ')
    if new_value != '': 
        substitutions[value] = new_value

changed_lines = []
for line in f:
    match_object = re.match(write_byte_re, line)
    if match_object is not None: 
        value = match_object.group(1)
        if value in substitutions: # not in the dictionary if the user said nothing
            new_value = substitutions[value]
            # modify line
            line = re.sub('\b%s\b' % value, new_value, line)
    changed_lines.append(line)

f.close()

# write output
f = open(filename, 'w')
f.writelines(changed_lines)
f.close()

You can avoid reading the file twice at the cost of a slightly more complicated code (left as an exercise to the reader)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜