2013-02-14 39 views
1

字符串我从一个Web应用程序在JSON中获取数据,包括各种蟒蛇转义字符,包括“\ n”和“\ r”清洗从转义字符与Python

我建立一个小的功能,清除从有问题的数据字符和空格,然后将其提供给sql。 (有问题的字符对使用sql的另一个应用程序有问题)。

目前的功能是:

bad_tokens = [",",";",".","!","'",".","-",'"',"@",r"\n",r"\r"] 

from types import StringType, UnicodeType 

def sql_text(sqltext, trim = None): 
    ''' 
    helper function to clean text inserted to sql from Priority problematic characters specified bad_tokens 

    ''' 
    thistype = type(sqltext) 
    if thistype not in (StringType, UnicodeType): 
     return sqltext 

    sqltext = sqltext.strip() #priority can't handle string starting with space 
    for token in bad_tokens: 
     sqltext = sqltext.replace(token,"") 
    sqltext = " ".join([i for i in sqltext.split(" ") if i != ""]) #priority can't handle string containing double spaces 

    if trim: 
     sqltext = sqltext[0:trim] 
    return sqltext 

这种方法工作正常进行定期字符,但似乎并没有清理\ n和\ r逃逸符号。将r(作为原始字符串)添加到转义符号也无济于事。

感谢您的帮助

编辑:我使用的ORM(SQLAlchemy的),所以我不直接访问DBAPI,虽然SQLAlchemy的确实由于SQL自动逸出大量对待这些字符作为sqlalchemy也是合法的。回到广场上 - 我需要正确清理字符串。

+3

为什么不使用数据库客户端库的SQL参数的功能呢?你在这里重新发明轮子。见http://wiki.python.org/moin/DbApiFaq – 2013-02-14 18:02:04

+0

......或见[这里](http://stackoverflow.com/questions/8115261/how-to-remove-all-the-escape-sequences-从-A-列表的串问题) – 2013-02-14 18:02:56

+0

@MartijnPieters我使用SQLAlchemy的已经但是\ r和\ n不被它逃脱至少我可以把结果告诉 – alonisser 2013-02-14 21:40:09

回答

-1
import re 

newbuff = re.sub("\n|\r| |moreoptions","",yourbuff)