是什么导致Python错误“错误的转义\ C"? [英] What causes Python error 'bad escape \C'?
问题描述
我刚刚编写了一个函数,该函数将查看文本文件并计算文本文件中True和False的所有实例.这是我的文件
I just wrote a function that will look at a text file and count all of the instances of True and False in the text file. Here is my file
ATOM 43 CA LYS A 5 14.038 15.691 37.608 1.00 15.15 C True
ATOM 52 CA CYS A 6 16.184 12.782 38.807 1.00 16.72 C True
ATOM 58 CA GLU A 7 17.496 12.053 35.319 1.00 14.06 C False
ATOM 67 CA VAL A 8 18.375 15.721 34.871 1.00 12.27 C True
ATOM 74 CA PHE A 9 20.066 15.836 38.288 1.00 12.13 C False
ATOM 85 CA GLN A 10 22.355 12.978 37.249 1.00 12.54 C False
这是我的代码
def TFCount(txtFileName):
with open(txtFileName, 'r') as e:
T = 0
F = 0
for record in e:
if(re.search(r'^ATOM\s+\d+\s+\CA\s+\w+\s+\w+\s+\d+\s+\d+\.\d+\s+\d+\.\d+\s+\d+\.\d+\s+\d+\.\d+\s+\d+\.\d+\s+\w+\s+\T', record)):
T += 1
else:
F += 1
print(T)
print(F)
我很抱歉,如果我的正则表达式很长且很繁琐,但是这是我知道计算文件中True发生次数的唯一方法.如您所见,每次程序遇到True时,它将对变量T加1,否则将给变量False加1.尝试运行该程序后,解释器返回错误:错误的转义符\ C.这个错误是什么意思?而我的代码是什么引起的呢?
I apologize if my regex is long and tedious to read, but this is the only way I know of counting the number of times True occurs in the file. As you can see, each time the program encounters True, it will add 1 to the variable T, otherwise it will add 1 to the variable False. After attempting to run the program, the interpreter returns error: bad escape \C. What does this error mean? And what in my code is causing it?
推荐答案
您在正则表达式的第一部分中有 \ C
You have \C
in the first part of the regex
r'^ATOM\s+\d+\s+\CA
您应该只写CA
r'^ATOM\s+\d+\s+CA
没有转义.
稍后您与 \ T
相同.
\ X
表示转义的 X
,大多数情况下是正则表达式中的特殊序列,例如 \ d
表示数字,或 \ s
表示空格.
\X
means escaped X
and most of the time is a special sequence in regex, e.g. \d
for a digit or \s
for a whitespace.
这篇关于是什么导致Python错误“错误的转义\ C"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!