#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    19
    Rep Power
    0

    Convert string to list


    Is there an easy way to convert a string that contains a list to a list? For example, '[1,2,3]' would convert to [1,2,3].

    /Fredrik
  2. #2
  3. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69

    split and eval


    Ok, if I may ask why would you want to put a list within a string? Anyway you could use split to break the string apart..

    >>> string = '[1,2,3]'
    >>> string = string[1:-1].split(',')
    >>> string
    ['1', '2', '3']
    >>>

    however, the entries within the list will be converted to strings.

    If your looking to so somthing more advanced than this you could pass the string to eval, the return value should be the list contained within the string (My prefered way to do it).

    >>> string = '[1,2,3]'
    >>> list = eval(string)
    >>> list
    [1, 2, 3]
    >>>

    Hope this helps.

    Have fun,
    Mark.
    Last edited by netytan; July 23rd, 2003 at 12:09 PM.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2009
    Location
    houston
    Posts
    6
    Rep Power
    0
    what is the indexing all about?

    >>> stg = "[1, 2, 3]"
    >>> lst1 = stg.split(',')
    >>> lst1
    ['[1', ' 2', ' 3]']
    >>> lst2 = stg[1:].split(',')
    >>> lst2
    ['1', ' 2', ' 3]']
    >>> lst3 = stg[:-1].split(',')
    >>> lst3
    ['[1', ' 2', ' 3']
    >>> lst4 = stg[1:-1].split(',')
    >>> lst4
    ['1', ' 2', ' 3']


    SCHEMATICALLY:
    >>> stg = "[1, 2, 3]" #stg itm,s are '[1', '2', '3]'; precedence?
    nul ['[1', '2', '3]'] #each itm is now a lst itm;
    [1:] [' 1', '2', '3]'] #shouldn't this slice remove itm #1?
    [:-1] ['[1', '2', '3' ] #and this slice, #3?
    [1:-1] [ '1', '2', '3' ] #and this, both? here 3 itm,s are stg,s;
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    439
    Rep Power
    67
    Originally Posted by imputerate
    SCHEMATICALLY:
    >>> stg = "[1, 2, 3]" #stg itm,s are '[1', '2', '3]'; precedence?
    Huh? The string items are the individual characters ("[", "1", "," etc.).

    [1:] [' 1', '2', '3]'] #shouldn't this slice remove itm #1?
    No, “item”, or more appropriately, character #0 (= the opening bracket).

    [:-1] ['[1', '2', '3' ] #and this slice, #3?
    No, the last character (= the closing bracket).
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2009
    Location
    houston
    Posts
    6
    Rep Power
    0
    SuperOscar; you nailed it; so, the premise of this thread, fuffen's

    i.e., "convert a 'string that contains a list' to a list"

    is flawed because the quotes of the string take precedence over the
    brackets of the list?

    "[1, 2, 3]"

    so, there is no list until the split creates one?

    ['[1', ' 2', ' 3]']

    and, what i said, incorrectly, about the "three items" in the string
    turns out to be true of the three items in that first list?

    hmmmm; is this "precedence of punctuation" like the precedence which
    informs arithmetical procedures? are there other snarls lurking out
    there?

    thanks for your insight; imputerate
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2008
    Posts
    96
    Rep Power
    45
    I'd like to add...

    python Code:
    >>> t = '[1,2,3,4]'
    >>> eval(t)
    [1, 2, 3, 4]
    >>> type(eval(t))
    <type 'list'>
    >>> type(t)
    <type 'str'>
    >>> s = eval(t)
    >>> type(s)
    <type 'list'>
    >>> s
    [1, 2, 3, 4]
    >>>
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2009
    Posts
    58
    Rep Power
    6
    its gr8...

    let me write method for list reversal .
    lis =[1,2,3,4,5]
    lis =lis[::-1]

    now lis will print the reverse.
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2009
    Location
    houston
    Posts
    6
    Rep Power
    0

    but what about the precedence?


    i'm losing the thread [you should pardon the expression];

    eval(string) conversion, and list reversal are all very well and good, but:

    are there formal orders of precedence for things like "...", '...', [...]...?

    is it always so that putting a list in a string will resorb the brackets into list items, as happened above '[1, 2, 3]'?
    "The string items are the individual characters ("[", "1", "," etc.)."
    and why wasn't the absence of a comma after the first bracket a problem?

    what would happen if there were two "lists" in the string?
    '[1, 2, 3],[4, 5, 6]'

    do the quotes always take precedence over the brackets? and so on...
    imputerate
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2009
    Location
    houston
    Posts
    6
    Rep Power
    0
    CORRECTION: i meant to say:
    is it always so that putting a list in a string will resorb the brackets into STRING items, as happened above '[1, 2, 3]'?

    Originally Posted by imputerate
    i'm losing the thread [you should pardon the expression];

    eval(string) conversion, and list reversal are all very well and good, but:

    are there formal orders of precedence for things like "...", '...', [...]...?

    --------------------------
    is it always so that putting a list in a string will resorb the brackets into list items, as happened above '[1, 2, 3]'?
    CORRECTION: i meant to say:
    is it always so that putting a list in a string will resorb the brackets into STRING items, as happened above '[1, 2, 3]'?
    ----------------------------

    "The string items are the individual characters ("[", "1", "," etc.)."
    and why wasn't the absence of a comma after the first bracket a problem?

    what would happen if there were two "lists" in the string?
    '[1, 2, 3],[4, 5, 6]'

    do the quotes always take precedence over the brackets? and so on...
    imputerate
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    439
    Rep Power
    67
    Originally Posted by imputerate
    are there formal orders of precedence for things like "...", '...', [...]...?
    Of course there is a formal order of precedence. Python would be a poor programming language unless you could be sure what always happens given a specific string of characters.

    Outermost characters are what matter. If you have "[1, 2, 3]", it’s a string. If you have [1, 2, 3], it’s a list of numbers (integers). ["1", "2", "3"] is a list of strings.

    is it always so that putting a list in a string will resorb the brackets into list items, as happened above '[1, 2, 3]'?
    That’s not “putting a list in a string”. It’s a string of arbitrary characters which happen to look like string to you.

    what would happen if there were two "lists" in the string?
    '[1, 2, 3],[4, 5, 6]'
    You would have a string of arbitrary characters.
  20. #11
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2010
    Posts
    2
    Rep Power
    0

    another problem


    I have a big corpus and I have the string in the following format:

    [('<RECIPE', '>')][('<TI', '>'), ('Cinnamon', 'NN'), ('Rolls', 'NNS'), ('<', 'TI>')][('<IN', '>'), ('1/2', 'CD'), ('ea', 'NN'), ('Sweet', 'JJ'), ('dough', 'NN'), ('mixture', 'NN'), ('<', 'IN>')][('<IN', '>'), ('1/2', 'CD'), ('c', 'NN'), ('Packed', 'JJ'), ('light', 'JJ'), ('brown', 'JJ'), ('sugar', 'NN'), ('<', 'IN>')]

    in a separate file. I got this after applying,
    tuples=[nltk.tag.str2tuple(t) for t in line.split()]

    Now I want to use it perform the chunking through regular expression, this part I know but I dunno how to manipulate this string so that it can be further used. (read the file and then apply chunker, if you want i can type this code here)

    How to convert the above string to list?
    its very very important :-)
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Posts
    624
    Rep Power
    35
    a) Thread from the dead, man! I was shocked and pleased to see a post from Netytan for a moment there.

    b) You had a string, you split it and it became a list, you str2tuple'd each item in the list and they became tuples, then you gathered the tuples into a list using a list comprehension. You don't have a string anymore, you have a list of tuples.
  24. #13
  25. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2010
    Posts
    2
    Rep Power
    0
    i tried to use list(sent) function. Now I have written a chunker which gives me the following error

    Traceback (most recent call last):
    File "C:\User\NLP\chunker.py", line 10, in <module>
    tree=cp.parse(sentences)
    File "C:\Program Files\Python\lib\site-packages\nltk\chunk\regexp.py", line 1183, in parse
    chunk_struct = parser.parse(chunk_struct, trace=trace)
    File "C:\Program Files\Python\lib\site-packages\nltk\chunk\regexp.py", line 994, in parse
    chunk_struct = Tree(self._top_node, chunk_struct)
    File "C:\Program Files\Python\lib\site-packages\nltk\tree.py", line 93, in __init__
    list.__init__(self, children)

    if I don't use list(sent) I get this :

    Traceback (most recent call last):
    File "C:\Users\NLP\chunker.py", line 10, in <module>
    tree=cp.parse(sent)
    File "C:\Program Files\Python\lib\site-packages\nltk\chunk\regexp.py", line 1183, in parse
    chunk_struct = parser.parse(chunk_struct, trace=trace)
    File "C:\Program Files\Python\lib\site-packages\nltk\chunk\regexp.py", line 994, in parse
    chunk_struct = Tree(self._top_node, chunk_struct)
    File "C:\Program Files\Python\lib\site-packages\nltk\tree.py", line 70, in __new__
    "string" % cls.__name__)
    TypeError: Tree() argument 2 should be a list, not a string

    and if you want here is my code:

    import nltk
    import re
    textfile = open('textfile.txt','r+')

    grammar=r"NP:{<DT>?<JJ>*<NN>}"
    cp=nltk.RegexpParser(grammar, trace=1)

    for sent in TTCorpus:
    #sentences=list(sent)
    tree=cp.parse(sent)
    print tree



    textfile.close()

    can you help me in this regard? its really important and urgent also :-(

IMN logo majestic logo threadwatch logo seochat tools logo