首页 > 解决方案 > 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 ...

标签: pythonregexpandas

解决方案


您可以使用

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代表单词边界)

推荐阅读