Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Context-sensitive delimiter
#4
Here is a way, using re.sub
from itertools import pairwise
import re

def our_split(data):
    level = 0
    position = [-1]

    def _sub(match):
        nonlocal level
        c = match.group(0)
        level += {'[': 1, ']': -1}.get(c, 0)
        if c == ',' and not level:
            position.append(match.start())

    re.sub(r'[\[\],]', _sub, data)
    position.append(len(data))
    return [data[u+1:v] for u, v in pairwise(position)]

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

    result = our_split(data)
    print(result)
Output:
['Richtung route', ' trend', ' way [route, direction]', ' tendency [political etc.]', ' course [direction]', ' direction [course, route]']
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,632 Nov-09-2023, 10:56 AM
Last Post: mg24
  Read csv file with inconsistent delimiter gracenz 2 1,255 Mar-27-2023, 08:59 PM
Last Post: deanhystad
  How does open context manager work? deanhystad 7 1,417 Nov-08-2022, 02:45 PM
Last Post: deanhystad
  Delimiter issue with a CSV file jehoshua 1 1,358 Apr-19-2022, 01:28 AM
Last Post: jehoshua
  Decimal context stevendaprano 1 1,084 Apr-11-2022, 09:44 PM
Last Post: deanhystad
  How to create new line '/n' at each delimiter in a string? MikeAW2010 3 2,919 Dec-15-2020, 05:21 PM
Last Post: snippsat
  Case sensitive checks kam_uk 2 2,048 Nov-30-2020, 01:25 AM
Last Post: bowlofred
  copy content of text file with three delimiter into excel sheet vinaykumar 0 2,398 Jul-12-2020, 01:27 PM
Last Post: vinaykumar
  How to print string multiple times separated by delimiter Mekala 1 1,979 May-23-2020, 09:21 AM
Last Post: Yoriz
  TextIOWrapper.tell() with Python 3.6.9 in context of 0D/0A fschaef 0 2,108 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