2016-02-10 49 views
3

我想讀一個文件並替換每個字符串「一個......一個」由「\ footnotemark」蟒紋/寫含有「 F」

with open('myfile', 'r') as myfile: 
    data = myfile.read() 
    data = re.sub('<a.+?</a>', '\footnotemark', data) 

不知何故Python中總是讓「\ footnotemark '到'\ x0cootnotemark'('\ f'到'\ x0c')。我試過到目前爲止

  • 逃逸: '{2個反斜線} footnotemark'
  • 原始字符串:R '\ footnotemark' 或R ' 「\ footnotemark」'

這些都不曾

示例輸入:

foo<a href="anything">asdasd</a> bar 

輸出示例:

foo\footnotemark bar 
+6

'R'\\ footnotemark'' –

+0

這給了我'\\ footnotemark' – enzian

+0

後的例如預期產出。順便說一句,你爲什麼要嘗試使用正則表達式替換html標籤? –

回答

3

假設Python2因爲你沒有提到任何關於版本

#/usr/bin/python 

import re 

# myfile is saved with utf-8 encoding 
with open('myfile', 'r') as myfile: 

    text = myfile.read() 
    print text 
    data = re.sub('<a.+?</a>', r'\\footnotemark', text) 

print data 

輸出

foo<a href="anything">asdasd</a> bar 
foo\footnotemark bar