Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Context-sensitive delimiter
#10
An alternative to using re.sub() is re.finditer(). This introduces an explicit loop instead of a callback function but the advantage is that the our_split() function becomes a generator which is cleaner.
import re

def our_split(data):
    depth = 0
    pos = -1

    for match in re.finditer(r'[\[\],]', data):
        match match.group(0):
            case ',':
                if depth == 0:
                    yield data[pos + 1 : (pos := match.start())]
            case '[':
                depth += 1
            case ']':
                depth -= 1

    yield data[pos + 1:]

if __name__ == '__main__':
    data = "Richtung route, trend, way [route, direction], tendency [political etc.], course [direction], direction [course, route]"

    result = list(our_split(data))
    print(result)
Reply


Messages In This Thread
Context-sensitive delimiter - by ZZTurn - May-15-2023, 08:19 AM
RE: Context-sensitive delimiter - by ZZTurn - May-15-2023, 05:08 PM
RE: Context-sensitive delimiter - by Gribouillis - May-15-2023, 05:21 PM
RE: Context-sensitive delimiter - by ZZTurn - May-15-2023, 06:58 PM
RE: Context-sensitive delimiter - by Gribouillis - May-15-2023, 07:51 PM
RE: Context-sensitive delimiter - by ZZTurn - May-15-2023, 09:38 PM
RE: Context-sensitive delimiter - by Gribouillis - May-15-2023, 09:50 PM
RE: Context-sensitive delimiter - by ZZTurn - May-15-2023, 10:10 PM
RE: Context-sensitive delimiter - by Gribouillis - May-16-2023, 07:31 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,552 Nov-09-2023, 10:56 AM
Last Post: mg24
  Read csv file with inconsistent delimiter gracenz 2 1,229 Mar-27-2023, 08:59 PM
Last Post: deanhystad
  How does open context manager work? deanhystad 7 1,383 Nov-08-2022, 02:45 PM
Last Post: deanhystad
  Delimiter issue with a CSV file jehoshua 1 1,338 Apr-19-2022, 01:28 AM
Last Post: jehoshua
  Decimal context stevendaprano 1 1,070 Apr-11-2022, 09:44 PM
Last Post: deanhystad
  How to create new line '/n' at each delimiter in a string? MikeAW2010 3 2,895 Dec-15-2020, 05:21 PM
Last Post: snippsat
  Case sensitive checks kam_uk 2 2,033 Nov-30-2020, 01:25 AM
Last Post: bowlofred
  copy content of text file with three delimiter into excel sheet vinaykumar 0 2,383 Jul-12-2020, 01:27 PM
Last Post: vinaykumar
  How to print string multiple times separated by delimiter Mekala 1 1,945 May-23-2020, 09:21 AM
Last Post: Yoriz
  TextIOWrapper.tell() with Python 3.6.9 in context of 0D/0A fschaef 0 2,096 Mar-29-2020, 09:18 AM
Last Post: fschaef

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020