如何在python中从左到右替换文本文件中的字符?



我有一个文本文件(*.txt),它的内容是"01110011",我想替换它这样:'00' ==> a,'01' ==> b,'10' ==> c,'11' ==> d从左到右。所以内容变成了'bdad'。根据这篇文章,我使用了下面的代码,但不幸的是,替换不是定向的(我的意思是它不是从左到右)。我可以请你帮我一下吗?

# Read in the file
with open('file.txt', 'r') as file :
filedata = file.read()
# Replace the target string
filedata = filedata.replace('00', 'a')
filedata = filedata.replace('01', 'b')
filedata = filedata.replace('10', 'c')
filedata = filedata.replace('11', 'd')
# Write the file out again
with open('file.txt', 'w') as file:
file.write(filedata)

创建一个新字符串,只替换偶数索引处的2字符子字符串:

repl = {
'00': 'a',
'01': 'b',
'10': 'c',
'11': 'd',
}

filedata = ''.join(repl[filedata[i:i+2]] for i in range(0, len(filedata), 2))

省略文件处理,您可以这样做:-

mystring = '01110011'
mymap = {'00': 'a', '01': 'b', '10': 'c', '11': 'd'}
newstring = ''
while len(mystring) >= 2:
newstring += mymap[mystring[:2]]
mystring = mystring[2:]
print(newstring)

这将有助于:

with open('file.txt', 'r') as file :
filedata = file.read()
New_String = ""
for i in range(0, len(filedata), 2):
if filedata[i:i+2] == "00" : New_String += "a"
if filedata[i:i+2] == "01" : New_String += "b"
if filedata[i:i+2] == "10" : New_String += "c"
if filedata[i:i+2] == "11" : New_String += "d"
print(New_String)

这是一个NumPy解决方案。

import numpy as np
# Read in the file
with open('file.txt', 'r') as file:
byte_array = np.fromfile(file, dtype='uint8').reshape(-1, 2)
result = np.full((byte_array.shape[0], 1), b' ')
result[np.all(byte_array == (48, 48), axis=1)] = b'a'
result[np.all(byte_array == (48, 49), axis=1)] = b'b'
result[np.all(byte_array == (49, 48), axis=1)] = b'c'
result[np.all(byte_array == (49, 49), axis=1)] = b'd'
# Write the file out again
with open('file.txt', 'w') as file:
file.write(result.tobytes().decode('utf-8'))

有关此方法的详细信息,请参阅此回答。

或者,更方便地,您可以将中间部分替换为:

repl = {
(48, 48): b'a',
(48, 49): b'b',
(49, 48): b'c',
(49, 49): b'd',
}
result = np.full((byte_array.shape[0], 1), b' ')
for k, v in repl.items():
result[np.all(byte_array == k, axis=1)] = v

最新更新