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

searching a pattern in a file

P: 4
how to search particular strings in a file. and display it plz send me the python command
Apr 27 '07 #1
Share this Question
Share on Google+
3 Replies


P: 15
I'm new to Python myself, but this I can answer. Though it really depends how you are handling that file, something like this works:

Expand|Select|Wrap|Line Numbers
  1. >>> s="hello, how are you?"
  2. >>> print "hell" in s
  3. True
or if it's a complex and varying pattern you're looking for you could use regular expressions,
http://www.amk.ca/python/howto/regex/
Apr 27 '07 #2

bvdet
Expert Mod 2.5K+
P: 2,851
how to search particular strings in a file. and display it plz send me the python command
This will return a string index list of the occurrences of a substring found in a file:
Expand|Select|Wrap|Line Numbers
  1. def indexList(s, item, i=0):
  2.     i_list = []
  3.     while True:
  4.         try:
  5.             i = s.index(item, i)
  6.             i_list.append(i)
  7.             i += 1
  8.         except:
  9.             break
  10.     return i_list
  11.  
  12. fStr = open('data_file').read()
  13. matchStr = 'some string'
  14. matchList = indexList(fStr, matchStr)
  15. print matchList
In my test case:
>>> [201, 327, 1439, 1488]
Apr 27 '07 #3

P: 4
This will return a string index list of the occurrences of a substring found in a file:
Expand|Select|Wrap|Line Numbers
  1. def indexList(s, item, i=0):
  2.     i_list = []
  3.     while True:
  4.         try:
  5.             i = s.index(item, i)
  6.             i_list.append(i)
  7.             i += 1
  8.         except:
  9.             break
  10.     return i_list
  11.  
  12. fStr = open('data_file').read()
  13. matchStr = 'some string'
  14. matchList = indexList(fStr, matchStr)
  15. print matchList
In my test case:
>>> [201, 327, 1439, 1488]
thanks dude.. it was so help full to me and i got good ideas to do more
May 2 '07 #4

Post your reply

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