python - Python - Pandas - 删除第一次出现的字符和修复字符串之间的内容
问题描述
想象一下,我有那个数据框:
data = {'Script': ["create table table_name ( col_1 string , col_2 string , col_3 string ) row format serde 'org.apache.hadoop.hive.serde2.lazy.lazysimpleserde' with properties ( 'field.delim' ='\t' , 'serialization.format' ='\t' , 'serialization.null.format'='' ) stored as inputformat 'org.apache.hadoop.mapred.textinputformat' outputformat 'org.apache.hadoop.hive.ql.io.hiveignorekeytextoutputformat' location 'hdfs://nameservice1/table_name'tblproperties ( 'parquet.compress'='snappy' );"]}
df = pd.DataFrame(data)
基本上,该列的内容是DDL:
create table table_name
(
col_1 string
, col_2 string
, col_3 string
)
row format serde 'org.apache.hadoop.hive.serde2.lazy.lazysimpleserde' with properties
(
'field.delim' ='\t'
, 'serialization.format' ='\t'
, 'serialization.null.format'=''
)
stored as inputformat 'org.apache.hadoop.mapred.textinputformat' outputformat 'org.apache.hadoop.hive.ql.io.hiveignorekeytextoutputformat' location 'hdfs://nameservice1/table_name'tblproperties
(
'parquet.compress'='snappy'
)
我需要做的是删除拳头“(”和“位置”一词之间的所有内容。基本上我的预期输出是以下内容:
create table table_name
(
col_1 string
, col_2 string
, col_3 string
)
location 'hdfs://nameservice1/table_name'tblproperties
(
'parquet.compress'='snappy'
)
为此,我正在尝试使用正则表达式方法:
df['DDL'] = df.Script.str.replace(r")", " } ").str.replace(r'<}^>location+>', "")
然而,结果并不是我们想要的:
create table table_name
(
col_1 string
, col_2 string
, col_3 string
}
row format serde 'org.apache.hadoop.hive.serde2.lazy.lazysimpleserde' with properties
(
'field.delim' ='\t'
, 'serialization.format' ='\t'
, 'serialization.null.format'='' } stored as inputformat 'org.apache.hadoop.mapred.textinputformat' outputformat 'org.apache.hadoop.hive.ql.io.hiveignorekeytextoutputformat' location 'hdfs://nameservice1/table_name'tblproperties ( 'parquet.compress'='snappy' }
;
我做错了什么?通过我的方法,我试图在 { 和 location ...
解决方案
您可以使用
df['DDL'] = df['Script'].str.replace(r"(?s)^([^)]*)\).*?\b(location)\b", r"\1\2")
查看正则表达式演示
细节
(?s)
-制作匹配换行符的内联re.DOTALL
选项.
^
- 字符串的开始([^)]*)
- 第 1 组(\1
在替换模式中):除此之外的任何 0+ 个字符)
\)
- 一个)
字符.*?
- 任何 0+ 字符,尽可能少(*?
是非贪婪量词)\b(location)\b
- 第 2 组(\2
在替换模式中)捕获整个单词location
(\b
代表单词边界)
推荐阅读
- json - 位置 471 处的 JSON 中的意外字符串
- api - 如何使用变量发送补丁 api 请求
- python - 为什么python3在文件写入方面比python2慢
- python-3.x - Python子类方法从超类方法继承装饰器
- python - 如何解决代码中的 KeyError,我是初学者
- sql - 计数功能和案例
- java - 单击 imageButton 后,如何最好地禁用其他 imageButton,并为变量分配所选 imageButton 的值?
- pdf - 如何在 Flutter 中不带括号的不同行中打印 pdf 列表?
- mongodb - 在分片集群上创建用户
- php - Symfony 4 在登录失败时检索用户的电子邮件