我正在使用Python替換SQL文件中的某些字符串。該字符串看起來這樣的:使用Python替換SQL中的某些文本
<img title="\frac{3}{8}" src="http://latex.codecogs.com/gif.latex?\dpi{50}&space;\fn_phv&space;\frac{3}{8}" alt="" />
基本上它包含了一小部分的HTML代碼。但現在我想用來替換:
<sup>3</sup>⁄<sub>8</sub>
取代它在SQL文件,我使用Python中的代碼,
for line in filedata:
re.sub(r'<img\b[^<]*(?<=title=")\\frac\{(\d+)\}\{(\d+)\}"[^<]*>', "<sup>\g<1></sup>⁄<sub>\g<2></sub>", line)
這不會改變數據,所以我也嘗試過這一點。
filedata1 = re.sub(r'<img\b[^<]*(?<=title=")\\frac\{(\d+)\}\{(\d+)\}"[^<]*>', "<sup>\g<1></sup>⁄<sub>\g<2></sub>", filedata)
這也沒有幫助我。需要一些幫助。
我全碼:
import re
with open('/Users/cnnlakshmen/Downloads/qz_question.sql', 'r') as fin:
filedata = fin.read()
for line in filedata:
re.sub(r'<img\b[^<]*(?<=title=")\\frac\{(\d+)\}\{(\d+)\}"[^<]*>', "<sup>\g<1></sup>⁄<sub>\g<2></sub>", line)
filedata1 = re.sub(r'<img\b[^<]*(?<=title=")\\frac\{(\d+)\}\{(\d+)\}"[^<]*>', "<sup>\g<1></sup>⁄<sub>\g<2></sub>", filedata)
print filedata1
# Write the file out again
with open('/Users/cnnlakshmen/Downloads/qz_question1.sql', 'w') as fin:
fin.write(filedata1)
每一個數據行看起來是這樣的:
(163, 'S001', 'T005', 'ST015', 'Medium', '1', 9, '1', '<p>The ratio of the number of children to the number of adults at a funfair was 2 : 5. <sup>1</sup>⁄<sub>5</sub>of the children were boys. If there were 120 more adults than children, how many girls were there at the funfair?</p>\n<p> </p>', 'without_image', '[{"value":"16","answer":"0"},{"value":"40","answer":"0"},{"value":"64","answer":"1"},{"value":"120","answer":"0"}]', '<p>5 -2 = 3</p>\n<p>3 units --> 120</p>\n<p>1 unit --> 120 ÷ 3 = 40</p>\n<p>2 units --> 40 x 2 = 80</p>\n<p>1 - <img title="\\small \\frac{1}{5}" src="http://latex.codecogs.com/gif.latex?\\small&space;\\frac{1}{5}" alt="" width="5" height="20" /> = <img title="\\small \\frac{4}{5}" src="http://latex.codecogs.com/gif.latex?\\small&space;\\frac{4}{5}" alt="" width="4" height="16" /></p>\n<p><img title="\\small \\frac{4}{5}" src="http://latex.codecogs.com/gif.latex?\\small&space;\\frac{4}{5}" alt="" width="4" height="16" /> x 80 = 64</p>', 'lakshmen K', NULL, '1', '0', '2015-05-03 15:54:19', '0000-00-00 00:00:00'),