简体   繁体   中英

regular expression match with word and join with matched

I have this problem that I could not find a solution for quite a while. My guess is that the best approach is via re, but I am open to any suggestions.

I have the text below in a list which I wrote to a text file to be imported by a different program for some calculation.

The problem is that I have to include matched line (ie []s=0) with similar []s=0 like this:[]s=0 -> p01:(s'=1) + p02:(s'=2). So, the first two lines must be combined by a + operator and so the following third and fourth line and so forth.

module main
[]s=0 -> p01:(s'=1);
[]s=0 -> p02:(s'=2);
[]s=1 -> p10:(s'=0);
[]s=1 -> p12:(s'=2);
[]s=2 -> p20:(s'=0);
[]s=2 -> p23:(s'=3);
[]s=3 -> p34:(s'=4);
[]s=4 -> p40:(s'=0);
[]s=4 -> p45:(s'=5);
[]s=4 -> p46:(s'=6);
[]s=5 -> p57:(s'=7);
[]s=6 -> p67:(s'=7);
[]s=7 -> p70:(s'=0);
endmodule

Assuming you have the data as strings?

data = ["[]s=0 -> p01:(s'=1);",
"[]s=0 -> p02:(s'=2);",
"[]s=1 -> p10:(s'=0);",
"[]s=1 -> p12:(s'=2);",
"[]s=2 -> p20:(s'=0);",
"[]s=2 -> p23:(s'=3);",
"[]s=3 -> p34:(s'=4);",
"[]s=4 -> p40:(s'=0);",
"[]s=4 -> p45:(s'=5);",
"[]s=4 -> p46:(s'=6);",
"[]s=5 -> p57:(s'=7);",
"[]s=6 -> p67:(s'=7);",
"[]s=7 -> p70:(s'=0);"]

dict_ = {}
for item in data:
    split = (item.split("=")[1].split(" ")[0])
    if not split in dict_:
        dict_[split] = item
    else:
        dict_[split] = dict_[split] + " + " + item

for key, value in dict_.items() :
    print (key, value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM