简体   繁体   中英

Counting and comparing some repeatedly strings appearances between other strings in Python 3

I have an input like this:

{"id": 123, "class": t1, "format": f1, "class-2": t1, ...}  
{"id": 456, "class": t2, "format": f1, ...}  
{"id": 567, "class": t1, "format": f2, "class-2": t2, "class-3": t1, ...}  

...

I want an output like this:

123 = t1  
456 = t2  
567 = t1

...
(567 classification compares how many times t1 appears against t2)

I am trying re.search but without success. It is a huge text file and I have put everything in the same line but I can not count correctly each class appearance between every id to compare.

I'm not 100% sure I understand what you want and since you didn't any code this is my attempt using Regex:

import re

string = """{"id": 123, "class": t1, "format": f1, "class-again": t1, ...}  
{"id": 456, "class": t2, "format": f1, ...}  
{"id": 567, "class": t1, "format": f2, "class-again": t2, "class-again": t1, ...} """

for id, cl in zip(re.findall('"id": (.+?),', string), 
                  re.findall('"class": (.+?),', string)):
  print('{} = {}'.format(id, cl))

Output:

123 = t1
456 = t2
567 = t1

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