Tue, October 10, 2006
{update:2007-01-15}
Jythonでよく使うテクニック(3) 特殊記号のエスケープ処理
ウェブページにコードを載せる場合、HTMLで使用できない < > などの特殊記号を エスケープする必要があります。 RSSフィードなどの生成時でもやはりエスケープが必要で、この手のコードは 手元にあると便利です。
convert.py
import sys
import java.lang as lang
import java.io as io
false=0
true=1
def read(file):
sb=lang.StringBuffer()
br=io.BufferedReader(io.FileReader(file))
while(true):
line=br.readLine()
if line==None:
break
line=lang.String(line).replaceAll("&","&")
line=lang.String(line).replaceAll("<","<")
line=lang.String(line).replaceAll(">",">")
line=lang.String(line).replaceAll("\"",""")
sb.append(line)
sb.append(lang.System.getProperty("line.separator"))
br.close()
return sb.toString()
file=io.File(sys.argv[1])
text=read(file)
print text
実行
$ jython covert.py foo.txt