python实现字符串完美拆分split()

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013468614/article/details/85410221

python实现字符串完美拆分

  • 函数:split()

例子

我们想要将以下字符串rule进行拆分。字符串表示的是一个规则,由“…”得到“…”。我们需要将规则中的条件属性与取值分别提取出来,存放在条件属性列表cf_list与值列表cv_list中,规则的结论的属性与取值也提取出来,分别存放结果属性列表rf_list与值列表rc_list
rule = '{age=Middle-aged,sex=Male,education=Bachelors}=>{native-country=United-States}'

代码

rule = '{age=Middle-aged,sex=Male,education=Bachelors}=>{native-country=United-States}'
c_s, r_s = s.split("=>")
c_list = c_s.split("{")[1].split("}")[0].split(",")
r = r_s.split("{")[1].split("}")[0]

cf_list = []
cv_list = []
for c in c_list:
    cf, cv = c.split("=")
    cf_list.append(cf)
    cv_list.append(cv)
rf, rv = r.split("=")

print(cf_list, cv_list, rf, rv)

输出结果:
([‘age’, ‘sex’, ‘education’], [‘Middle-aged’, ‘Male’, ‘Bachelors’], ‘native-country’, ‘United-States’)

部分代码说明:

  • 1
    c_s, r_s = s.split("=>")

‘=>’为分隔符,将字符串rule分成两部分:{age=Middle-aged,sex=Male,education=Bachelors}{native-country=United-States}

  • 2
c_list = c_s.split("{")[1].split("}")[0].split(",")

该行代码将字符串{age=Middle-aged,sex=Male,education=Bachelors}中的{}滤掉后,将每个条件分开并存储在列表中。具体地,c_s.split("{"){将字符串{age=Middle-aged,sex=Male,education=Bachelors}拆分成包含两个元素的列表[’’, ‘age=Middle-aged,sex=Male,education=Bachelors}’],第一个元素为空字符串,不包含任何信息,故只取拆分结果的第二个元素c_s.split("{")[1]。同理,c_s.split("{")[1].split("}")[0]是在之前拆分的基础上以}对字符串拆分,并滤掉空字符串。

猜你喜欢

转载自blog.csdn.net/u013468614/article/details/85410221