Given a string how do you create a list containing sublists?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Meghna J Patel
    New Member
    • Oct 2010
    • 3

    Given a string how do you create a list containing sublists?

    you have to write a function which takes in the parameter text (which is a string). And returns a list containing sublist. each sublist contains the sentence in the text. sentences are separated using "." , "?", or "!"

    example
    if text is "hello, how are you? i am fine thank you. what a lovely day!"
    the result should be [["hello", "how", "are", "you"],
    ["i", "am", "fine", "thank", "you"],["what", "a", "lovely", "day"]]

    all text will be entered in as lowercase
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    This interactive session should help:
    Code:
    >>> T="hello, how are you? i am fine thank you. what a lovely day!"
    >>> T.replace("?",".")
    'hello, how are you. i am fine thank you. what a lovely day!'
    >>> T=T.replace("?",".")
    >>> T=T.replace("!",".")
    >>> T
    'hello, how are you. i am fine thank you. what a lovely day.'
    >>> T=T.replace(",","")
    >>> T
    'hello how are you. i am fine thank you. what a lovely day.'
    >>> L=T.split(".")
    >>> L
    ['hello how are you', ' i am fine thank you', ' what a lovely day', '']
    >>> L2=[]
    >>> for l in L:
    	L2.append(l.split(" "))
    
    	
    >>> 
    >>> L2
    [['hello', 'how', 'are', 'you'], ['', 'i', 'am', 'fine', 'thank', 'you'], ['', 'what', 'a', 'lovely', 'day'], ['']]
    >>>
    It's not quite right - you need to remove the final full-stop from the test with something like:
    Code:
    if T[-1]==".":
        T=T[:-1]

    Comment

    • Meghna J Patel
      New Member
      • Oct 2010
      • 3

      #3
      Thanks

      Thanks a lot for your time and help. I tested the code and it works as expected.

      Comment

      Working...