473,606 Members | 2,381 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

split a string with quoted parts into list

hi there

i'm experimanting with imaplib and came across stringts like
(\HasNoChildren ) "." "INBOX.Sent Items"
in which the quotes are part of the string.

now i try to convert this into a list. assume the string is in the variable
f, then i tried
f.split()
but i end up with
['(\\HasNoChildr en)', '"."', '"INBOX.Sent ', 'Items"']
so due to the sapce in "Sent Items" its is sepearted in two entries, what i
don't want.

is there another way to convert a string with quoted sub entries into a list
of strings?

thanks a lot, olli
Jul 18 '05 #1
5 3264
oliver wrote:
i'm experimanting with imaplib and came across stringts like
(\HasNoChildren ) "." "INBOX.Sent Items"
in which the quotes are part of the string.

now i try to convert this into a list. assume the string is in the variable
f, then i tried
f.split()
but i end up with
['(\\HasNoChildr en)', '"."', '"INBOX.Sent ', 'Items"']
so due to the sapce in "Sent Items" its is sepearted in two entries, what i
don't want.

is there another way to convert a string with quoted sub entries into a list
of strings?


Try the standard module shlex
(http://www.python.org/dev/doc/devel/...le-shlex.html). It might be
that the quoting rules are not exactly the ones you need, though.

Daniel
Jul 18 '05 #2
> is there another way to convert a string with quoted sub entries into a
list of strings?


try the csv-module.
--
Regards,

Diez B. Roggisch
Jul 18 '05 #3
oliver wrote:
hi there

i'm experimanting with imaplib and came across stringts like
(\HasNoChildren ) "." "INBOX.Sent Items"
in which the quotes are part of the string.

now i try to convert this into a list. assume the string is in the variable
f, then i tried
f.split()
but i end up with
['(\\HasNoChildr en)', '"."', '"INBOX.Sent ', 'Items"']
so due to the sapce in "Sent Items" its is sepearted in two entries, what i
don't want.

is there another way to convert a string with quoted sub entries into a list
of strings?

In Twisteds protocols/imap4.py module there is a function called
parseNestedPare ns() that can be ripped out of the module.

I have used it for another project and put it into this attachment.

--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

"""
This code was stolen from Twisteds protocols/imap4.py module
"""

import types, string

class IMAP4Exception( Exception):
def __init__(self, *args):
Exception.__ini t__(self, *args)

class MismatchedNesti ng(IMAP4Excepti on):
pass

class MismatchedQuoti ng(IMAP4Excepti on):
pass

def wildcardToRegex p(wildcard, delim=None):
wildcard = wildcard.replac e('*', '(?:.*?)')
if delim is None:
wildcard = wildcard.replac e('%', '(?:.*?)')
else:
wildcard = wildcard.replac e('%', '(?:(?:[^%s])*?)' % re.escape(delim ))
return re.compile(wild card, re.I)

def splitQuoted(s):
"""Split a string into whitespace delimited tokens

Tokens that would otherwise be separated but are surrounded by \"
remain as a single token. Any token that is not quoted and is
equal to \"NIL\" is tokenized as C{None}.

@type s: C{str}
@param s: The string to be split

@rtype: C{list} of C{str}
@return: A list of the resulting tokens

@raise MismatchedQuoti ng: Raised if an odd number of quotes are present
"""
s = s.strip()
result = []
inQuote = inWord = start = 0
for (i, c) in zip(range(len(s )), s):
if c == '"' and not inQuote:
inQuote = 1
start = i + 1
elif c == '"' and inQuote:
inQuote = 0
result.append(s[start:i])
start = i + 1
elif not inWord and not inQuote and c not in ('"' + string.whitespa ce):
inWord = 1
start = i
elif inWord and not inQuote and c in string.whitespa ce:
if s[start:i] == 'NIL':
result.append(N one)
else:
result.append(s[start:i])
start = i
inWord = 0
if inQuote:
raise MismatchedQuoti ng(s)
if inWord:
if s[start:] == 'NIL':
result.append(N one)
else:
result.append(s[start:])
return result
def splitOn(sequenc e, predicate, transformers):
result = []
mode = predicate(seque nce[0])
tmp = [sequence[0]]
for e in sequence[1:]:
p = predicate(e)
if p != mode:
result.extend(t ransformers[mode](tmp))
tmp = [e]
mode = p
else:
tmp.append(e)
result.extend(t ransformers[mode](tmp))
return result
def collapseStrings (results):
"""
Turns a list of length-one strings and lists into a list of longer
strings and lists. For example,

['a', 'b', ['c', 'd']] is returned as ['ab', ['cd']]

@type results: C{list} of C{str} and C{list}
@param results: The list to be collapsed

@rtype: C{list} of C{str} and C{list}
@return: A new list which is the collapsed form of C{results}
"""
copy = []
begun = None
listsList = [isinstance(s, types.ListType) for s in results]

pred = lambda e: isinstance(e, types.TupleType )
tran = {
0: lambda e: splitQuoted(''. join(e)),
1: lambda e: [''.join([i[0] for i in e])]
}
for (i, c, isList) in zip(range(len(r esults)), results, listsList):
if isList:
if begun is not None:
copy.extend(spl itOn(results[begun:i], pred, tran))
begun = None
copy.append(col lapseStrings(c) )
elif begun is None:
begun = i
if begun is not None:
copy.extend(spl itOn(results[begun:], pred, tran))
return copy


def parseNestedPare ns(s, handleLiteral = 1):
"""Parse an s-exp-like string into a more useful data structure.

@type s: C{str}
@param s: The s-exp-like string to parse

@rtype: C{list} of C{str} and C{list}
@return: A list containing the tokens present in the input.

@raise MismatchedNesti ng: Raised if the number or placement
of opening or closing parenthesis is invalid.
"""
s = s.strip()
inQuote = 0
contentStack = [[]]
try:
i = 0
L = len(s)
while i < L:
c = s[i]
if inQuote:
if c == '\\':
contentStack[-1].append(s[i+1])
i += 2
continue
elif c == '"':
inQuote = not inQuote
contentStack[-1].append(c)
i += 1
else:
if c == '"':
contentStack[-1].append(c)
inQuote = not inQuote
i += 1
elif handleLiteral and c == '{':
end = s.find('}', i)
if end == -1:
raise ValueError, "Malformed literal"
literalSize = int(s[i+1:end])
contentStack[-1].append((s[end+3:end+3+lit eralSize],))
i = end + 3 + literalSize
elif c == '(' or c == '[':
contentStack.ap pend([])
i += 1
elif c == ')' or c == ']':
contentStack[-2].append(content Stack.pop())
i += 1
else:
contentStack[-1].append(c)
i += 1
except IndexError:
raise MismatchedNesti ng(s)
if len(contentStac k) != 1:
raise MismatchedNesti ng(s)
return collapseStrings (contentStack[0])
if __name__=='__ma in__':

r = '(\Noinferiors \Unmarked) "/" "INBOX"(\Unmark ed) "/" "test"(\Noinfer iors \Unmarked) "/" "Sent Items"(\Noinfer iors \Unmarked) "/" "Calendar"(\Noi nferiors \Unmarked) "/" "Checklist"(\Un marked) "/" "Cabinet"(\Noin feriors \Marked) "/" "Trash"(\Unmark ed) "/" "INBOX.Sent"(\U nmarked) "/" "Sent"'

parsedParens = parseNestedPare ns(r)
print parsedParens
for i in range(0, len(parsedParen s), 3):
(flags, seperator, folderName) = parsedParens[i:i+3]
print flags
print seperator
print folderName
Jul 18 '05 #4
oliver wrote:
i'm experimanting with imaplib and came across stringts like
(\HasNoChildren ) "." "INBOX.Sent Items"
in which the quotes are part of the string.

now i try to convert this into a list. assume the string is in the variable
f, then i tried
f.split()
but i end up with
['(\\HasNoChildr en)', '"."', '"INBOX.Sent ', 'Items"']
so due to the sapce in "Sent Items" its is sepearted in two entries, what i
don't want. is there another way to convert a string with quoted sub entries into a list
of strings?


First break into strings, then space-split the non-strings.

def splitup(somestr ing):
gen = iter(somestring .split('"'))
for unquoted in gen:
for part in unquoted.split( ):
yield part
yield gen.next().join ('""')

--Scott David Daniels
Sc***********@A cm.Org
Jul 18 '05 #5
Oliver -

Here is a simpler approach, hopefully more readable, using pyparsing
(at http://pyparsing.sourceforge.net). I also added another test word
to your sample input line, one consisting of a lone pair of double
quotes, signifying an empty string. (Be sure to remove leading '.'s
from Python text - necessary to retain program indentation which Google
Groups otherwise collapses.)

-- Paul
..data = r"""
..(\HasNoChildr en) "." "INBOX.Sent Items" ""
.."""
..
..from pyparsing import printables,Word ,dblQuotedStrin g,OneOrMore
..
..nonQuoteChars = "".join( [ c for c in printables if c not in '"'] )
..word = Word(nonQuoteCh ars) | dblQuotedString
..
..words = OneOrMore(word)
..
..for s in words.parseStri ng(data):
.. print ">%s<" % s
..
Gives:
(\HasNoChildre n)<
"."<
"INBOX.Sent Items"<
""<
But really, I'm guessing that you'd rather not have the quote
characters in there either. It's simple enough to have pyparsing
remove them when a dblQuotedString is found:

..# add a parse action to remove the double quote characters
..# one of the beauties of parse actions is that there is no need to
..# verify that the first and last characters are "'s - this function
..# is never called unless the tokens in tokenslist match the
..# required expression
..def removeDblQuotes (st,loc,tokensl ist):
.. return tokenslist[0][1:-1]
..dblQuotedStri ng.setParseActi on( removeDblQuotes )
..
..for s in words.parseStri ng(data):
.. print ">%s<" % s
..
Gives:(\HasNoChildre n)<
.<
INBOX.Sent Items<
<


Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
2130
by: Luka Milkovic | last post by:
Hello, I have a little problem and although it's little it's extremely difficult for me to describe it, but I'll try. I have written a program which extracts certain portions of my received e-mail. The content of the e-mail is actually predictable, it has one very long list of numbers, something looking like this:
13
10406
by: Larry L | last post by:
Access is noted for bloating a database when you add and delete records frequently. I have always had mine set to compact on close, and that works great. Now after everyone's advice I split my database, so the data is in a second (back-end) database with all the tables linked. However, now when I close the database, it compacts the front end, since that's what's open, and the back-end grows. I now have to manually open and close the...
4
728
by: William Stacey [MVP] | last post by:
Would like help with a (I think) a common regex split example. Thanks for your example in advance. Cheers! Source Data Example: one "two three" four Optional, but would also like to ignore pairs of brackets like: "one" <tab> "two three" ( four "five six" ) Want fields like:
4
1592
by: Roshawn | last post by:
Hi, I am retrieving a list of book titles from a web service. What I'd like to do is shorten the titles, if possible. For example, there is a book titled "Malicious Mobile Code: Virus Protection for Windows". It would be nice if I could trim the title down to the colon (it would just say Malicious Mobile Code). Is there an easy way to accomplish this task?
4
6033
by: Michele Petrazzo | last post by:
Hello ng, I don't understand why split (string split) doesn't work with the same method if I can't pass values or if I pass a whitespace value: >>> "".split() >>> "".split(" ") But into the doc I see:
3
3624
by: Dave | last post by:
I'm calling string.Split() producing output string. I need direct access to its enumerator, but would greatly prefer an enumerator strings and not object types (as my parsing is unsafe casting from object to string frequently). Basically generics and not its non- generic counterpart. string str1 = "abc: value1 def: value2 ghi: value3"; char delimiterChars = { '\t' }; string tokens = str1.Split(delimiterChars);
10
2505
by: teddyber | last post by:
Hello, first i'm a newbie to python (but i searched the Internet i swear). i'm looking for some way to split up a string into a list of pairs 'key=value'. This code should be able to handle this particular example string : qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess
2
3126
by: Andy B | last post by:
I don't know if this is even working or not but here is the problem. I have a gridview that I databound to a dictionary<string, stringcollection: Contract StockContract = new Contract(); StockContract.Dictionary = ContractDictionary<string, string>(); GridView1.DataSource=StockContract.Dictionary; So far so good. Now I assign something to the Dictionary collection through some textboxes and a button:
6
1596
by: Joel Koltner | last post by:
I normally use str.split() for simple splitting of command line arguments, but I would like to support, e.g., long file names which-- under windows -- are typically provided as simple quoted string. E.g., myapp --dosomething --loadthis "my file name.fil" ....and I'd like to get back a list wherein ListEntry="my file name.fil" , but just running str.split() on the above string creates:
0
7955
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8440
Oralloy
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8431
jinu1996
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8096
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6773
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5966
isladogs
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5466
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3937
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
1300
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.