I am looking for a simple split function to create a list of entries
from a string which contains quoted elements. Like in 'google'
search.
eg string = 'bob john "johnny cash" 234 june'
and I want to have a list of ['bob', 'john, 'johnny cash', '234',
'june']
I wondered about using the csv routines, but I thought I would ask the
experts first.
There maybe a simple function, but as yet I have not found it.
Thanks
Richard 5 2037
Paul Melis wrote:
Hi,
mosscliffe wrote:
>I am looking for a simple split function to create a list of entries from a string which contains quoted elements. Like in 'google' search.
eg string = 'bob john "johnny cash" 234 june'
and I want to have a list of ['bob', 'john, 'johnny cash', '234', 'june']
I wondered about using the csv routines, but I thought I would ask the experts first.
There maybe a simple function, but as yet I have not found it.
Here a not-so-simple-function using regular expressions. It repeatedly
matched two regexps, one that matches any sequence of characters except
a space and one that matches a double-quoted string. If there are two
matches the one occurring first in the string is taken and the matching
part of the string cut off. This is repeated until the whole string is
matched. If there are two matches at the same point in the string the
longer of the two matches is taken. (This can't be done with a single
regexp using the A|B operator, as it uses lazy evaluation. If A matches
then it is returned even if B would match a longer string).
Here a slightly improved version which is a bit more compact and which
removes the quotes on the matched output quoted string.
import re
def split_string(s) :
pat1 = re.compile('[^" ]+')
pat2 = re.compile('"([^"]*)"')
parts = []
m1 = pat1.search(s)
m2 = pat2.search(s)
while m1 or m2:
if m1 and m2:
if m1.start(0) < m2.start(0):
match = 1
elif m2.start(0) < m1.start(0):
match = 2
else:
if len(m1.group(0) ) len(m2.group(0) ):
match = 1
else:
match = 2
elif m1:
match = 1
else:
match = 2
if match == 1:
part = m1.group(0)
s = s[m1.end(0):]
else:
part = m2.group(1)
s = s[m2.end(0):]
parts.append(pa rt)
m1 = pat1.search(s)
m2 = pat2.search(s)
return parts
print split_string('b ob john "johnny cash" 234 june')
print split_string('" abc""abc"')
Hi,
mosscliffe wrote:
I am looking for a simple split function to create a list of entries
from a string which contains quoted elements. Like in 'google'
search.
eg string = 'bob john "johnny cash" 234 june'
and I want to have a list of ['bob', 'john, 'johnny cash', '234',
'june']
I wondered about using the csv routines, but I thought I would ask the
experts first.
There maybe a simple function, but as yet I have not found it.
Here a not-so-simple-function using regular expressions. It repeatedly
matched two regexps, one that matches any sequence of characters except
a space and one that matches a double-quoted string. If there are two
matches the one occurring first in the string is taken and the matching
part of the string cut off. This is repeated until the whole string is
matched. If there are two matches at the same point in the string the
longer of the two matches is taken. (This can't be done with a single
regexp using the A|B operator, as it uses lazy evaluation. If A matches
then it is returned even if B would match a longer string).
import re
def split_string(s) :
pat1 = re.compile('[^ ]+')
pat2 = re.compile('"[^"]*"')
parts = []
m1 = pat1.search(s)
m2 = pat2.search(s)
while m1 or m2:
if m1 and m2:
# Both match, take match occurring earliest in the string
p1 = m1.group(0)
p2 = m2.group(0)
if m1.start(0) < m2.start(0):
part = p1
s = s[m1.end(0):]
elif m2.start(0) < m1.start(0):
part = p2
s = s[m2.end(0):]
else:
# Both match at the same string position, take longest match
if len(p1) len(p2):
part = p1
s = s[m1.end(0):]
else:
part = p2
s = s[m2.end(0):]
elif m1:
part = m1.group(0)
s = s[m1.end(0):]
else:
part = m2.group(0)
s = s[m2.end(0):]
parts.append(pa rt)
m1 = pat1.search(s)
m2 = pat2.search(s)
return parts
>>s = 'bob john "johnny cash" 234 june' split_string( s)
['bob', 'john', '"johnny cash"', '234', 'june']
>>>
Paul
mosscliffe <mc********@goo glemail.comwrot e:
I am looking for a simple split function to create a list of entries
from a string which contains quoted elements. Like in 'google'
search.
eg string = 'bob john "johnny cash" 234 june'
and I want to have a list of ['bob', 'john, 'johnny cash', '234',
'june']
I wondered about using the csv routines, but I thought I would ask the
experts first.
There maybe a simple function, but as yet I have not found it.
You probably need to specify the problem more completely. e.g. Can the
quoted parts of the strings contain quote marks? If so how what are the
rules for escaping them. Do two spaces between a word mean an empty field
or still a single string delimiter.
Once you've worked that out you can either use re.split with a suitable
regular expression, or use the csv module specifying your desired dialect:
>>class mosscliffe(csv. Dialect):
delimiter = ' '
quotechar = '"'
doublequote = False
skipinitialspac e = False
lineterminator = '\r\n'
quoting = csv.QUOTE_MINIM AL
>>csv.register_ dialect("mosscl iffe", mosscliffe) string = 'bob john "johnny cash" 234 june' for row in csv.reader([string], dialect="mosscl iffe"):
print row
['bob', 'john', 'johnny cash', '234', 'june']
Thank you very much for all for your replies.
I am now much wiser to using regex and CSV.
As I am quite a newbie, I have had my 'class' education improved as
well.
Many thanks again
Richard
On May 16, 12:48 pm, Duncan Booth <duncan.bo...@i nvalid.invalid>
wrote:
mosscliffe <mcl.off...@goo glemail.comwrot e:
I am looking for a simple split function to create a list of entries
from a string which contains quoted elements. Like in 'google'
search.
eg string = 'bob john "johnny cash" 234 june'
and I want to have a list of ['bob', 'john, 'johnny cash', '234',
'june']
I wondered about using the csv routines, but I thought I would ask the
experts first.
There maybe a simple function, but as yet I have not found it.
You probably need to specify the problem more completely. e.g. Can the
quoted parts of the strings contain quote marks? If so how what are the
rules for escaping them. Do two spaces between a word mean an empty field
or still a single string delimiter.
Once you've worked that out you can either use re.split with a suitable
regular expression, or use the csv module specifying your desired dialect:
>class mosscliffe(csv. Dialect):
delimiter = ' '
quotechar = '"'
doublequote = False
skipinitialspac e = False
lineterminator = '\r\n'
quoting = csv.QUOTE_MINIM AL
>csv.register_d ialect("mosscli ffe", mosscliffe) string = 'bob john "johnny cash" 234 june' for row in csv.reader([string], dialect="mosscl iffe"):
print row
['bob', 'john', 'johnny cash', '234', 'june']
On May 16, 12:42 pm, mosscliffe <mcl.off...@goo glemail.comwrot e:
I am looking for a simple split function to create a list of entries
from a string which contains quoted elements. Like in 'google'
search.
eg string = 'bob john "johnny cash" 234 june'
and I want to have a list of ['bob', 'john, 'johnny cash', '234',
'june']
I wondered about using the csv routines, but I thought I would ask the
experts first.
There maybe a simple function, but as yet I have not found it.
See 'split' from 'shlex' module:
>>s = 'bob john "johnny cash" 234 june' import shlex shlex.split(s )
['bob', 'john', 'johnny cash', '234', 'june']
>>>
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: J. W. McCall |
last post by:
Hello,
I need to split a string as per string.strip(), but with a modification:
I want it to recognize quoted strings and return them as one list item,
regardless of any whitespace within the quoted string.
For example, given the string:
'spam "the life of brian" 42'
|
by: Mark Harrison |
last post by:
What is the best way to process a text file of delimited strings?
I've got a file where strings are quoted with at-signs, @like this@.
At-signs in the string are represented as doubled @@.
What's the most efficient way to process this? Failing all
else I will split the string into characters and use a FSM,
but it seems that's not very...
|
by: JeffM |
last post by:
Quick C# question:
I have comma delimited values in a string array that I want to pass to
seperate variables. Any tips on splitting the array?
Thanks in advance!
JM
|
by: Perseus |
last post by:
Hi
To split a single string we do the following
#
myString= "bannana, bowling balls, juice"
string singleArray= myString.split(',');
#
This gives
singleArray = "bannana" etc.
|
by: conspireagainst |
last post by:
I'm having quite a time with this particular problem:
I have users that enter tag words as form input, let's say for a photo or a topic of discussion. They are allowed to delimit tags with spaces and commas, and can use quotes to encapsulate multiple words.
An example:
tag1, tag2 tag3, "tag4 tag4, tag4" tag5, "tag6 tag6"
So, as we can...
| |
by: shadow_ |
last post by:
Hi i m new at C and trying to write a parser and a string class.
Basicly program will read data from file and splits it into lines then
lines to words. i used strtok function for splitting data to lines it
worked quite well but srttok isnot working for multiple blank or
commas. Can strtok do this kind of splitting if it cant what should i
use...
|
by: yogi_bear_79 |
last post by:
I have a simple string (i.e. February 27, 2008) that I need to split
into three parts. The month, day, and year. Splitting into a string
array would work, and I could convert day and years to integers
later. I've bene looking around, and everything I see seems more
complicated than it should be! Help!
|
by: spreadbetting |
last post by:
I'm trying to split a string into an separate arrays but the data is
only delimited by a comma. The actual data is one long string but the
info is in a regular format and repeats after every five ~'s .
i.e the data may be returned as
1.01~11844.69~0.0~0.0~2.0~1.02~117.3~0.0~0.0~0.0~1.03~66.82~0.0~0.0~0.0~1.0
4~300.0~0.0~0.0~0.0~
|
by: xyz |
last post by:
I have a string
16:23:18.659343 131.188.37.230.22 131.188.37.59.1398 tcp 168
for example lets say for the above string
16:23:18.659343 -- time
131.188.37.230 -- srcaddress
22 --srcport
131.188.37.59 --destaddress
1398 --destport
tcp --protocol
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it. ...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |