gpt4 book ai didi

python - 为有效的 MySQL 列名过滤字符串

转载 作者:行者123 更新时间:2023-11-30 22:52:54 25 4
gpt4 key购买 nike

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

我已经删除了这个列表

[' ', '*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 个字符在我的表中为列表中的每个条目创建一列。

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

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

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

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

最佳答案

使用这个正则表达式:

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_'

此外,如果您想要用 _ 替换任何其他字符,只需将该字符添加到 Regex 中的square braces。例如,您还需要替换 #。然后 regex 将变为 re.sub(r'[-/*$&.\s#]+','_',column_to_create[:20])

关于python - 为有效的 MySQL 列名过滤字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27580640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com