我有一个这种格式的文本文件:
b'Chapter 1 \xe2\x80\x93 BlaBla'
b'Boy\xe2\x80\x99s Dead.'
我想读这些台词,并把它们隐藏起来
Chapter 1 - BlaBla
Boy's Dead.
并在同一个文件中替换它们。我已经尝试过用
print(line.encode("UTF-8", "replace"))
进行编码和解码了,但没有成功
strings = [
b'Chapter 1 \xe2\x80\x93 BlaBla',
b'Boy\xe2\x80\x99s Dead.',
for string in strings:
print(string.decode('utf-8', 'ignore'))
--output:--
Chapter 1 – BlaBla
Boy’s Dead.
并在同一个文件中替换它们。
世界上没有一种计算机编程语言能做到这一点。您必须将输出写入新文件,删除旧文件,并将新文件重命名为旧文件。但是,python的
fileinput
模块可以为您执行该过程:
import fileinput as fi
import sys
with open('data.txt', 'wb') as f:
f.write(b'Chapter 1 \xe2\x80\x93 BlaBla\n')
f.write(b'Boy\xe2\x80\x99s Dead.\n')
with open('data.txt', 'rb') as f:
for line in f:
print(line)
with fi.input(
files = 'data.txt',
inplace = True,
backup = '.bak',
mode = 'rb') as f:
for line in f:
string = line.decode('utf-8', 'ignore')
print(string, end="")
~/python_programs$ python3.4 prog.py
b'Chapter 1 \xe2\x80\x93 BlaBla\n'
b'Boy\xe2\x80\x99s Dead.\n'
~/python_programs$ cat data.txt
Chapter 1 – BlaBla
Boy’s Dead.
编辑:
import fileinput as fi
import re
pattern = r"""
\\ #Match a literal slash...
x #Followed by an x...
[a-f0-9]{2} #Followed by any hex character, 2 times
repl = ''
with open('data.txt', 'w') as f:
print(r"b'Chapter 1 \xe2\x80\x93 BlaBla'", file=f)
print(r"b'Boy\xe2\x80\x99s Dead.'", file=f)
with open('data.txt') as f:
for line in f:
print(line.rstrip()) #Output goes to terminal window
with fi.input(
files = 'data.txt',
inplace = True,
backup = '.bak') as f:
for line in f:
line = line.rstrip()[2:-1]
new_line = re.sub(pattern, "", line, flags=re.X)
print(new_line) #Writes to file, not your terminal window
~/python_programs$ python3.4 prog.py
b'Chapter 1 \xe2\x80\x93 BlaBla'
b'Boy\xe2\x80\x99s Dead.'
~/python_programs$ cat data.txt
Chapter 1 BlaBla
Boys Dead.
您的文件不包含二进制数据,因此您可以在
text mode
中读取(或写入)它。这只是一个正确逃离事物的问题。
以下是第一部分:
print(r"b'Chapter 1 \xe2\x80\x93 BlaBla'", file=f)
Python将字符串中的某些
backslash escape sequences
转换为其他东西。python转换的反斜杠转义序列之一是格式:
\xNN #=> e.g. \xe2
反斜杠转义序列有四个字符长,但是python将反斜杠转义序列转换为单个字符。
但是,我需要将这四个字符中的每一个写到我创建的示例文件中。为了防止python将反斜杠转义序列转换为一个字符,您可以用另一个字符转义开头的'\':
\\xNN
但是由于懒惰,我不想遍历您的字符串并手动转义每个反斜杠转义序列,所以我使用了:
r"...."
r string
为您转义所有反斜杠。因此,python将
\xNN
序列的所有四个字符写入文件。
下一个问题是
replacing a backslash in a string using a regex
--我想这是你的问题。当文件包含
\
时,python将其读入字符串为
\\
,以表示文字反斜杠。因此,如果文件包含以下四个字符:
\xe2
python将其读入字符串,如下所示:
"\\xe2"
印刷时看上去如下:
\xe2
底线是:如果可以在打印出来的字符串中看到'\‘,那么反斜杠将在字符串中转义。要查看字符串中真正的内容,您应该始终使用
repr()
。
string = "\\xe2"