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

Character index in line

P: 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
Share this Question
Share on Google+
3 Replies

bartonc
Expert 5K+
P: 6,596
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
Expert Mod 2.5K+
P: 2,851
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

Expert 100+
P: 511
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.