Searching Text (Python)

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
vegaseat vegaseat is online now Online Oct 4th, 2005, 1:04 am |
0
Here is a generator function using find() to do a search for all the occurances of a substring in a text. It will give you all the positions/indexes within the text where the substring is located. The sample text here can be replaced by text read in from a file.
Quick reply to this message  
Python Syntax
  1. # find the indexes of all occurances of a substring in a text
  2. # tested with Python24 vegaseat 03oct2005
  3.  
  4. str1 = \
  5. '''Many many years ago when I was twenty three,
  6. I got married to a widow, who was pretty as could be.
  7. This widow had a grown-up daughter
  8. who had much hair of red.
  9. My father fell in love with her,
  10. and soon the two were wed.
  11.  
  12. This made my dad my son-in-law
  13. and changed my very life.
  14. My daughter was my mother,
  15. for she was my father's wife.
  16.  
  17. To complicate the matters worse,
  18. although it brought me joy,
  19. I soon became the father
  20. of a bouncing baby boy.
  21.  
  22. My little baby then became
  23. a brother-in-law to dad,
  24. and so became my uncle,
  25. which made me very sad.
  26.  
  27. For if he was my uncle,
  28. it also made him brother
  29. to the widow's grown-up daughter,
  30. who of course, was my stepmother.
  31.  
  32. Father's wife then had a son,
  33. who kept them on the run.
  34. This boy became my grandson,
  35. for he was my daughter's son.
  36.  
  37. My wife is now my mother's mother
  38. and makes me rather blue.
  39. Because, although she is my wife,
  40. she's my grandmother too.
  41.  
  42. If my wife is my grandmother,
  43. then I am her grandchild.
  44. Every time I think of it,
  45. it simply drives me wild.
  46.  
  47. For now I have become
  48. the strangest case you ever saw.
  49. As the husband of my grandmother,
  50. I am my own grandpa!'''
  51.  
  52. def findSubstring(text, substring):
  53. """position pos (index) is moved up for each call to this generator"""
  54. pos = -1
  55. while True:
  56. # move index up on next call
  57. pos = text.find(substring, pos + 1)
  58. # not found or done
  59. if pos < 0:
  60. break
  61. yield pos
  62.  
  63.  
  64. substring = 'daughter'
  65. for index in findSubstring(str1, substring):
  66. print "'%s' is at index %d" % (substring, index)

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC