• Function:split()

example

We want to split the following string rule. A string represents a rule, defined by “…” By “…” . We need to extract the conditional attributes and values in the rules and store them in the conditional attribute list CF_list and the value list cv_list, as well as the conclusion attributes and values of the rules and store the result attribute list RF_list and the value list RC_list respectively. rule = ‘{age=Middle-aged,sex=Male,education=Bachelors}=>{native-country=United-States}’

code

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)
Copy the code

Output: ([‘age’, ‘sex’, ‘education’], [‘ middle-aged ‘, ‘Male’, ‘Bachelors’], ‘native country’, ‘United States’)

Code description:

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

{age= aged,sex=Male,education=Bachelors} and {native-country=United States}

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

This line filters out the {and} in the string {age= middle-aged,sex=Male,education=Bachelors} to separate each condition and store it in the list. In particular, C_s.split (“{“) splits the string {age= middle-aged,sex=Male,education=Bachelors} into a list of two elements [“, ‘age= middle-aged,sex=Male,education=Bachelors}’], the first element is an empty string, so only the second element c_s.split(“{“)[1]. Similarly, c_s.split(“{“)[1].split(“}”)[0] splits the string with} and filters out the empty string.