By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,050 Members | 1,020 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,050 IT Pros & Developers. It's quick & easy.

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

P: 3
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
Oct 26 '10 #1
Share this Question
Share on Google+
2 Replies


Expert 100+
P: 391
This interactive session should help:
Expand|Select|Wrap|Line Numbers
  1. >>> T="hello, how are you? i am fine thank you. what a lovely day!"
  2. >>> T.replace("?",".")
  3. 'hello, how are you. i am fine thank you. what a lovely day!'
  4. >>> T=T.replace("?",".")
  5. >>> T=T.replace("!",".")
  6. >>> T
  7. 'hello, how are you. i am fine thank you. what a lovely day.'
  8. >>> T=T.replace(",","")
  9. >>> T
  10. 'hello how are you. i am fine thank you. what a lovely day.'
  11. >>> L=T.split(".")
  12. >>> L
  13. ['hello how are you', ' i am fine thank you', ' what a lovely day', '']
  14. >>> L2=[]
  15. >>> for l in L:
  16.     L2.append(l.split(" "))
  17.  
  18.  
  19. >>> 
  20. >>> L2
  21. [['hello', 'how', 'are', 'you'], ['', 'i', 'am', 'fine', 'thank', 'you'], ['', 'what', 'a', 'lovely', 'day'], ['']]
  22. >>> 
It's not quite right - you need to remove the final full-stop from the test with something like:
Expand|Select|Wrap|Line Numbers
  1. if T[-1]==".":
  2.     T=T[:-1]
Oct 26 '10 #2

P: 3
Thanks a lot for your time and help. I tested the code and it works as expected.
Oct 26 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.