How to split lines with mixed parts [closed] Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to split lines with mixed parts [closed] without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have text lines constructed by one of template:

  1. The song’s title (singer) (the year of song).
  2. The song’s title (then singer (the year of song)).

The difference between templates is the year of song inside or outside of singer’s parentheses.

I want split every line into three parts:

  1. The song’s title
  2. Singer
  3. The year of song

Small example

Ring Ring (ABBA (1973))
Waterloo (ABBA) (1974)
If I Don’t Write This Song Someone I Love Will Die (Hello Saferide) (2005)
My Best Friend (Hello Saferide (2005))

I try use RexExp with logical OR

import re

the_lines = ("Ring Ring (ABBA (1973))",
             "Waterloo (ABBA) (1974)",
             "If I Don’t Write This Song Someone I Love Will Die (Hello Saferide) (2005)",
             "My Best Friend (Hello Saferide (2005))",
             )
pattern = r"((.*) ((.*)) ((d*)))|((.*) ((.*((d*)))))"

for line in the_lines:
    title, artist, year = re.split(pattern, line)
    print(title, artist, year)

But this result is redundant, it get 8 groups.

Answer

Just use split() and strip() to get the result:

s = """Ring Ring (ABBA (1973))
Waterloo (ABBA) (1974)
If I Don’t Write This Song Someone I Love Will Die (Hello Saferide) (2005)
My Best Friend (Hello Saferide (2005))"""

s = [[word.strip(")") for word in line.split(" (")] for line in s.split("n")]

print(*s, sep="n")

Output:

['Ring Ring', 'ABBA', '1973']
['Waterloo', 'ABBA', '1974']
['If I Don’t Write This Song Someone I Love Will Die', 'Hello Saferide', '2005']
['My Best Friend', 'Hello Saferide', '2005']
  1. s.split("n") get each line in text
  2. for each line, line.split(" (") return a list of [title, singer, year))] or [title, singer), year)]
  3. for each list, word.strip(")") strip ) from singer and year.
We are here to answer your question about How to split lines with mixed parts [closed] - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji