2013-02-14 42 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)