Method of python to realize perfect string splitting split of
- 2021-07-22 10:01:35
- OfStack
Function: split ()
Example
We want to split the following string rule. The string represents a rule, and "…" is obtained from "…". We need to extract the condition attributes and values in the rules and store them in the condition attribute list cf_list and the value list cv_list. The conclusion attributes and values of the rules are also extracted and stored in 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)
Output:
([ ' age', ' sex', ' education'], [ ' Middle-aged', ' Male', ' Bachelors'], ' native-country', ' United-States')
Partial code description:
1.
c_s, r_s = s.split("=>")
'= > 'Is a separator that divides the string rule into two parts: {age=Middle-aged, sex=Male, education=Bachelors} and {native-country=United-States}
2.
c_list = c_s.split("{")[1].split("}")[0].split(",")
This line filters out {and} in the string {age=Middle-aged, sex=Male, education=Bachelors}, separates each condition and stores it in a list. Specifically, 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 and contains no information, so only the second element of the split result, c_s. split ("{") [1] is taken. Similarly, c_s]. split ("}") [0] splits strings with} on top of previous splits and filters out empty strings.