position.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from pyparsing import *
  2. text = """Lorem ipsum dolor sit amet, consectetur adipisicing
  3. elit, sed do eiusmod tempor incididunt ut labore et dolore magna
  4. aliqua. Ut enim ad minim veniam, quis nostrud exercitation
  5. ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
  6. aute irure dolor in reprehenderit in voluptate velit esse cillum
  7. dolore eu fugiat nulla pariatur. Excepteur sint occaecat
  8. cupidatat non proident, sunt in culpa qui officia deserunt
  9. mollit anim id est laborum"""
  10. # find all words beginning with a vowel
  11. vowels = "aeiouAEIOU"
  12. initialVowelWord = Word(vowels,alphas)
  13. # Unfortunately, searchString will advance character by character through
  14. # the input text, so it will detect that the initial "Lorem" is not an
  15. # initialVowelWord, but then it will test "orem" and think that it is. So
  16. # we need to add a do-nothing term that will match the words that start with
  17. # consonants, but we will just throw them away when we match them. The key is
  18. # that, in having been matched, the parser will skip over them entirely when
  19. # looking for initialVowelWords.
  20. consonants = ''.join(c for c in alphas if c not in vowels)
  21. initialConsWord = Word(consonants, alphas).suppress()
  22. # using scanString to locate where tokens are matched
  23. for t,start,end in (initialConsWord|initialVowelWord).scanString(text):
  24. if t:
  25. print(start,':', t[0])
  26. # add parse action to annotate the parsed tokens with their location in the
  27. # input string
  28. def addLocnToTokens(s,l,t):
  29. t['locn'] = l
  30. t['word'] = t[0]
  31. initialVowelWord.setParseAction(addLocnToTokens)
  32. for ivowelInfo in (initialConsWord | initialVowelWord).searchString(text):
  33. if not ivowelInfo:
  34. continue
  35. print(ivowelInfo.locn, ':', ivowelInfo.word)
  36. # alternative - add an Empty that will save the current location
  37. def location(name):
  38. return Empty().setParseAction(lambda s,l,t: t.__setitem__(name,l))
  39. locateInitialVowels = location("locn") + initialVowelWord("word")
  40. # search through the input text
  41. for ivowelInfo in (initialConsWord | locateInitialVowels).searchString(text):
  42. if not ivowelInfo:
  43. continue
  44. print(ivowelInfo.locn, ':', ivowelInfo.word)