我有一个文本文件,需要我以二进制阅读并以二进制文字写出。没问题。我需要用XS掩盖社会安全号码,通常很容易:
text = re.sub("\bd{3}-d{2}-{4}\b","XXX-XX-XXXX", text)
这是我要解析的文本的示例:
more stuff here
CHILDREN�S 001-02-0003 get rid of that
stuff goes here
not001-02-0003
but ssn:001-02-0003
我需要将其变成:
more stuff here
CHILDREN�S XXX-XX-XXXX get rid of that
stuff goes here
not001-02-0003
but ssn:XXX-XX-XXXX
超级!因此,现在我试图在二进制中写下相同的正则义务。这是我所拥有的,它是"工作",但天哪,它根本不正确:
line = re.sub(b"\B(x000|x001|x002|x003|x004|x005|x006|x007|x008|x009)(x000|x001|x002|x003|x004|x005|x006|x007|x008|x009)(x000|x001|x002|x003|x004|x005|x006|x007|x008|x009)x00-(x000|x001|x002|x003|x004|x005|x006|x007|x008|x009)(x000|x001|x002|x003|x004|x005|x006|x007|x008|x009)x00-(x000|x001|x002|x003|x004|x005|x006|x007|x008|x009)(x000|x001|x002|x003|x004|x005|x006|x007|x008|x009)(x000|x001|x002|x003|x004|x005|x006|x007|x008|x009)(x000|x001|x002|x003|x004|x005|x006|x007|x008|x009)\B", b"x00Xx00Xx00Xx00-x00Xx00Xx00-x00Xx00Xx00Xx00X", line)
注意:
- 在儿童中的垃圾,必须像这样保持
- 需要到边界,因此第四行不会被掩盖
我的正则是一系列数字吗?我只是不知道该怎么做。我的单词边界仅起作用向后 b而不是 b,呃。
update :我也尝试过:
line = re.sub(b"[x30-x39]", b"x58", line)
这是每个数字都可以做到的,但是如果我尝试做一些简单的事情,例如:
line = re.sub(b"[x30-x39][x30-x39]", b"x58x58", line)
它不再匹配任何东西,任何想法为什么?
您可以尝试:
import re
rx = re.compile(r'bd{3}-d{2}-d{4}b')
with open("test.txt", "rb") as fr, open("test2.txt", "wb+") as fp:
repl = rx.sub('XXX-XX-XXXX', fr.read())
fp.write(repl)
这将每个垃圾字符保持原样,并将其写入test2.txt
。
请注意,当您不希望每个后斜线逃脱时,可以在Python
中使用r'string here'
。