Reputation: 597
I am reading a file from the web row by row and each row is a list. The list has three columns visibly separated by this pattern: +++$+++
.
this is my code:
with closing(requests.get(url, stream=True)) as r:
reader = csv.reader(codecs.iterdecode(r.iter_lines(), 'latin-1'))
for i, row in enumerate(reader):
if i < 5:
t = row[0].split('(\s\+{3}\$\+{3}\s)+')
print(t)
I have tried to split the list using this instruction in python3.6 and can't get it to work. Any suggestion is well appreciated:
the list:
['m0 +++$+++ 10 things i hate about you +++$+++ http://www.dailyscript.com/scripts/10Things.html']
['m1 +++$+++ 1492: conquest of paradise +++$+++ http://www.hundland.org/scripts/1492-ConquestOfParadise.txt']
['m2 +++$+++ 15 minutes +++$+++ http://www.dailyscript.com/scripts/15minutes.html']
['m3 +++$+++ 2001: a space odyssey +++$+++ http://www.scifiscripts.com/scripts/2001.txt']
['m4 +++$+++ 48 hrs. +++$+++ http://www.awesomefilm.com/script/48hours.txt']
this is my regex expression:
row[0].split('(\s\+{3}\$\+{3}\s)+')
each row has only one component -> row[0]
when I print the result is not splitting the row.
Upvotes: 0
Views: 3727
Reputation: 36
Doing
row[0].split(' +++$+++ ')
should give you exactly what you wanted without regex.
Upvotes: 1
Reputation: 47
Assuming you don't want to use split(), if you want to relax things and return a tuple maybe this can help.
Input
import re
input = '''['m0 +++$+++ 10 things i hate about you +++$+++ http://www.dailyscript.com/scripts/10Things.html']
['m1 +++$+++ 1492: conquest of paradise +++$+++ http://www.hundland.org/scripts/1492-ConquestOfParadise.txt']
['m2 +++$+++ 15 minutes +++$+++ http://www.dailyscript.com/scripts/15minutes.html']
['m3 +++$+++ 2001: a space odyssey +++$+++ http://www.scifiscripts.com/scripts/2001.txt']
['m4 +++$+++ 48 hrs. +++$+++ http://www.awesomefilm.com/script/48hours.txt']'''
output = re.findall('\[\'([\S\s]+?)[\s]+[\+]{3}\$[\+]{3}[\s]+([\S\s]+?)[\s][\+]{3}\$[\+]{3}[\s]+([\S\s]+?)\'\]', input)
print(output)
Output:
[('m0', '10 things i hate about you', 'http://www.dailyscript.com/scripts/10Things.html'), ('m1', '1492: conquest of paradise', 'http://www.hundland.org/scripts/1492-ConquestOfParadise.txt'), ('m2', '15 minutes', 'http://www.dailyscript.com/scripts/15minutes.html'), ('m3', '2001: a space odyssey', 'http://www.scifiscripts.com/scripts/2001.txt'), ('m4', '48 hrs.', 'http://www.awesomefilm.com/script/48hours.txt')]
.
.
I' also trying to experiment with an alternating regex, but for the life of me, I can't get the formula to work haha.. eventually. I'll post it later, but hopefully the above helps
Upvotes: 0