过滤字符串以获取有效的MySQL列名称

时间:2014-12-20 13:20:49

标签: python mysql python-3.x

我一直在从网站上抓取数据。

我已将此列表删除

[' ', '*One child under 12 years old stays free using existing bedding.', '24 hour front desk', 'Bar / Lounge', 'Business centre', 'Concierge', 'Dry cleaning / laundry service', ... 

到目前为止,这种情况已被刮掉,而且还会刮掉更多(大约20个)。

我想通过获取前20个字符在List中为列表中的每个条目创建一个列。

以下是我如何过滤这些条目以生成有效的MySQL列名。

column_name = column_to_create[:20].replace(" ","_").replace("/","_").replace("*","_").replace("-","_").replace("$","_").replace("&","_").replace(".","_")

我知道它不包含许多无效字符。

如何过滤以获取有效的列名?任何代码较少的解决方案或任何Reg-Ex ???

2 个答案:

答案 0 :(得分:0)

使用此Regex

column_name = re.sub(r'[-/*$&.\s]+','_',column_to_create[:20])

演示:

>>> import re
>>> st = "replace/    these**characters---all$$of&them....with_"
>>> re.sub(r'[-/*$&.\s]+','_',st)
'replace_these_characters_all_of_them_with_'

此外,如果您要使用_替换任何其他字符,只需将该字符添加到正则表达式中的方括号即可。比方说,您还需要替换#。然后正则表达式将变为re.sub(r'[-/*$&.\s#]+','_',column_to_create[:20])

答案 1 :(得分:0)

Python具有翻译功能,您可以使用它轻松地将一个字符更改为另一个字符,或删除字符。我使用它是这样的(前3行设置,第4行实际上使用它。)

    norm   =  string.maketrans(' _,','---') # space underscore comma to dash
    keep   =  "-@'$%{}[]~#().&^+=/\/:"
    toss   =  string.translate(norm,norm,string.letters+string.digits+keep)

    toName = toName.translate(norm,toss)