What causes Python error 'bad escape \C'?

浪尽此生 提交于 2021-02-04 07:35:26

问题


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

And here is my code

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)

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?


回答1:


You have \C in the first part of the regex

r'^ATOM\s+\d+\s+\CA

you should write just CA

r'^ATOM\s+\d+\s+CA

without escaping.

Later you have the same with \T.

\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.



来源:https://stackoverflow.com/questions/53327992/what-causes-python-error-bad-escape-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!