469,592 Members | 1,782 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,592 developers. It's quick & easy.

Character index in line

1
Hi, friends I want to do a bit advanced search in a file
I want to get a word and its previous and next words
I think I need the index of my search word or there any other solutions

I am waiting your suggestions, thanks
Aug 3 '07 #1
3 2101
bartonc
6,596 Expert 4TB
Hi, friends I want to do a bit advanced search in a file
I want to get a word and its previous and next words
I think I need the index of my search word or there any other solutions

I am waiting your suggestions, thanks
A regular expression employing groups would do the trick. Basically you'd write a pattern that matched any whole word followed by your keyword followed by any word and assign them each to a group.
Aug 3 '07 #2
bvdet
2,851 Expert Mod 2GB
Following are a couple of ways:
Expand|Select|Wrap|Line Numbers
  1. s = 'Try to find the words preceding and following a key word.'
  2. keyw = 'preceding'
  3. patt = re.compile(r'[a-zA-Z]+ (?=%s)|%s|(?<=%s) [a-zA-Z]+' % (keyw, keyw, keyw))
  4. print [w.strip() for w in patt.findall(s)]
  5.  
  6. sList = s.split()
  7. i = sList.index(keyw)
  8. words = [sList[i-1], sList[i], sList[i+1]]
  9. print words
Output:
>>> ['words', 'preceding', 'and']
['words', 'preceding', 'and']
>>>
Aug 3 '07 #3
ghostdog74
511 Expert 256MB
Expand|Select|Wrap|Line Numbers
  1. >>> alist=['first','second' ,'search','next','nexttwo']
  2. >>> alist.index("search")
  3. 2
  4. >>> alist[alist.index("search") + 1 ]
  5. 'next'
  6. >>> alist[alist.index("search") - 1 ]
  7. 'second'
  8. >>>
  9.  
Aug 3 '07 #4

Post your reply

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

Similar topics

3 posts views Thread by Michael Loomington | last post: by
2 posts views Thread by dont bother | last post: by
38 posts views Thread by Haines Brown | last post: by
6 posts views Thread by Tony Tortora | last post: by
13 posts views Thread by Ivan | last post: by
13 posts views Thread by =?Utf-8?B?YXVsZGg=?= | last post: by
4 posts views Thread by guiromero | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.