我正在使用 pyparsing 在“CREATE TABLE”之后添加分号(“;”)。如果我有这个输入:
CREATE TABLE A ( B VARCHAR(255) )
该程序将给出下一个输出:
CREATE TABLE A ( B VARCHAR(255) );
当周围有评论时就会出现问题,如下所示:
CREATE TABLE A ( B VARCHAR(255) )
--Comment
程序提供的地方:
CREATE TABLE A ( B VARCHAR(255) )
--Comment
;
这是代码:
import pyparsing as par
alphanumsword = par.Word(par.alphanums + "_")
element = "(" + alphanumsword + ")" | alphanumsword
row = par.OneOrMore(element)
rows = row + par.OneOrMore("," + row) | row
semicolon = par.Literal(";")
comment1 = par.Literal("--") + par.restOfLine + par.LineEnd()
createtable = par.CaselessLiteral("create") + par.CaselessLiteral("table")
+ alphanumsword + "(" + rows + ")" + ~semicolon
createtable.ignore(comment1)
createtable.ignore(par.cStyleComment)
text = \
"""
CREATE TABLE PERSON
(
/* Comment */
/*
Comment
*/
ID VARCHAR(255),
NAME VARCHAR(255), -- Comment
--- Comment
ADDRESS VARCHAR(255) NULL, -- Comment
CONSTRAINT PK_PERSON PRIMARY KEY (ID)
)
-- Comment
CREATE TABLE A ( B VARCHAR(255) )
"""
text_list = list(text)
offset = 0
for t,s,e in createtable.scanString(text):
print "(", t, ",", s, ",", e, ")"
print "||", text[s:e], "||"
text_list.insert(e + offset, ';')
offset += 1
print "".join(text_list)