Python中的字符串替换
我有一个文本文件,里面有这样的内容:
WriteByte(0x6000, 0x28); // Register Value ...
WriteByte(0x6002, 0x02); //
WriteByte(0x6004, 0x08); //
我需要把0x28替换成用户输入的值。
这意味着我需要把0x28替换成用户提供的值,比如0x35或0x38等等。
而且我不能只指望文件里只有0x28,可能还有其他值需要被用户提供的内容替换。
另外,由于这个文本文件是手动写的,里面可能会有多余的空格,也可能没有。
WriteByte(0x6000,0x28); // Register Value ...
或者
WriteByte( 0x6000 , 0x28); // Register Value ...
我试过用string.replace
,但这可能无法处理所有的情况。
除了使用正则表达式,还有什么更好的方法吗?
1 个回答
0
根据下面的讨论,如果你想找到所有WriteBytes的第二个参数,并提示用户进行替换,可以按照以下步骤操作:
先解析文件,找出所有WriteBytes的第二个参数,使用正则表达式来帮助你,并把这些参数存储在一个集合里(集合会自动处理重复的值)
对于你找到的所有值,询问用户想要替换成什么,并把这些替换值存储在一个字典里
再读一遍文件,进行替换,把修改过的行和未修改的行一起存储在一个列表里
最后,把这些数据写回到磁盘上。
示例代码:
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()
你可以通过稍微复杂一点的代码来避免读取文件两次(这个留给读者自己尝试)