pyzuki

grep_phone.py

Sep 11th, 2011
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.95 KB | None | 0 0
  1. # grep_phone.py
  2.  
  3. import re, sys
  4.  
  5. #def get_last_path():
  6.     #f = open(choice_path, 'r')
  7.     #lines = []
  8.     #for line in f:
  9.         #lines.append(line)
  10.     #f.close()
  11.     #last_path = lines[0]
  12.     #return last_path
  13.    
  14. #def accept_last_choice(last_path):
  15.     #print("Last choice was:", get_filename_from_path(last_path))
  16.     #answer = input("If accept last choice, Enter nothing; if don't, enter anything: ")
  17.     #return answer, last_path
  18.  
  19. #def get_filename_from_path(path):
  20.     #idx = path.rfind('\\')
  21.     #filename = path[idx+1:]
  22.     #return filename
  23.  
  24. #def choose_file_to_grep(file_list, last_path, answer):
  25.     #if answer == '':
  26.         #return last_path
  27.     #else:
  28.         #print("file list:")
  29.     #for i,x  in enumerate(file_list):
  30.         #print(i, get_filename_from_path(file_list[i]))
  31.     #while True:
  32.         #try:
  33.             #idx = int(input("Enter index of file in file list: "))
  34.             #if not 0 <= idx <= len(file_list)-1:
  35.                 #continue
  36.         #except ValueError:
  37.             #print('You did not enter an integer')
  38.             #continue
  39.         #return file_list[idx]
  40.  
  41. def urls(line):
  42.     if "}}}" in line:
  43.         idx = line.find('}}}')
  44.         line = line[:idx]
  45.         idx = line.rfind('http:')
  46.         url_ = line[idx:]
  47.         return url_
  48.     else:
  49.         return ""
  50.    
  51.  
  52. def clean(line, chr_):
  53.     """
  54.    Cleans lines in RTF files such as those above. Heavy lifting is done when line has a URL.
  55.    If a line has a URL at the end, it first extracts the URL, cleans the line,
  56.    then returns the cleaned line with the URL replaced at the end.
  57.    
  58.    If there are one or more strings in line beginning with chr_ (e.g., '\\',
  59.    """
  60.     url_ = urls(line)
  61.     if '{' in line:
  62.         idx = line.find('{')
  63.         return line[:idx] + url_
  64.     n = None
  65.     while True:
  66.         if chr_ in line:
  67.             idx = line.find(chr_)
  68.             n = idx + 1
  69.             # return if end of line is reached
  70.             if n >= len(line):
  71.                 return line
  72.             while True:
  73.                 if n < len(line) and line[n] != ' ':
  74.                     str_ = line[idx:n]
  75.                 # remove str_ and return line + _url, if space char reached in line
  76.                 else:
  77.                     str_ = line[idx:n]
  78.                     line = line.replace(str_, "")
  79.                     return line + url_
  80.                 n += 1
  81.         else:
  82.             return line + url_
  83.        
  84. def clean_file(path):
  85.     f = open(path, 'r')
  86.     line_list = []
  87.     for line in f:
  88.         line_list.append(clean(line, '\\'))
  89.     f.close()
  90.     return line_list
  91.  
  92. def print_instructions():
  93.     print("Key (ignoring quotes): ' ' is a space, 'x' means any char except ' ' or '='")
  94.     print("If 1st 2 chars are:")
  95.     print("'=x' --> case insensitive, word")
  96.     print("' =' --> case sensitive, word")
  97.     print("' x' --> case sensitive, string")
  98.     print("'xx' --> case insensitive, string")
  99.     print("If search string = '==' --> start a new search of phone.rtf")
  100.     #print("'==' --> start a new search of same file")
  101.    
  102. def print_searching(count):
  103.     if count == 0:
  104.         print("Searching", filename)
  105.     else:
  106.         print("Searching", filename, "within hits so far,")
  107.        
  108. def grep_line_list(line_list, line_list0, filename):
  109.     search = input("Enter search string or word; enter nothing to quit: ")
  110.     if search == '==':
  111.         line_list = line_list0
  112.         print()
  113.         print("Starting a fresh search of", filename)
  114.         search = input("Enter search string or word; enter nothing to quit: ")
  115.     if not search:
  116.         print("Bye")
  117.         sys.exit()
  118.     #'x': case insensitive
  119.     elif search[0] != ' ':
  120.         #'xx': case insensitive; not word
  121.         if search[0] != '=':
  122.             p = re.compile(search, re.I)
  123.         #'x=': case insensitive; word
  124.         else:
  125.             search = "\\b" + search[1:] + "\\b"
  126.             p = re.compile(search, re.I)
  127.     #' ': case sensitive
  128.     else:
  129.         #' x': case sensitive; not word
  130.         if search[1] != '=':
  131.             search = search[1:]
  132.             p = re.compile(search)
  133.         #' =': case sensitive; word
  134.         else:
  135.             search = search[2:]
  136.             search = "\\b" + search + "\\b"
  137.             p = re.compile(search)
  138.        
  139.     line_list2 = []
  140.     count = 0
  141.     for line in line_list:
  142.         if p.search(line):
  143.             line_list2.append(line)
  144.             count += 1
  145.     line_list = line_list2
  146.     return line_list, count
  147.    
  148. def print_results(line_list, count):
  149.     print("==================================")
  150.     print_count_only = input("print hits plus count? Enter nothing; print count only? Enter anything: ")
  151.  
  152.     if print_count_only == "":
  153.         print("Printing hits and count:")
  154.         line_list.sort()
  155.         for line in line_list:
  156.             print()
  157.             print(line)
  158.         print()
  159.         print("count =", count)
  160.     else:
  161.         print("Printing count only:")
  162.         print()
  163.         print("count =", count)
  164.     print()
  165.    
  166. def write_data(choice_path, data, mode):
  167.     datafile = open(choice_path, mode)
  168.     datafile.write(data)
  169.     datafile.close()
  170.    
  171. def main():
  172.     count = 0
  173.     line_list0 = clean_file(path)
  174.     line_list = line_list0
  175.     print_instructions()
  176.     while True:
  177.         print_searching(count)
  178.         line_list, count = grep_line_list(line_list, line_list0, filename)
  179.         print()
  180.         print_results(line_list, count)
  181.        
  182. #file_list = ['C:\\Users\Dick\Desktop\Documents\\ActiveWords.rtf',
  183.              #'C:\\Users\Dick\Desktop\Documents\\ActiveWords_test.rtf',
  184.              #'C:\\Users\Dick\Desktop\Documents\\phone.rtf',
  185.              #'C:\\Users\Dick\Desktop\Documents\\phone_test.rtf',
  186.              #'C:\\Users\Dick\Desktop\Documents\\test.rtf']
  187.  
  188. path = 'C:\\Users\Dick\Desktop\Documents\\Notes\\phone.rtf'
  189. filename = 'phone.rtf'
  190. #choice_path = 'C:\\p31_data\choice.txt'
  191.  
  192. if __name__ == '__main__':
  193.     main()
Advertisement
Add Comment
Please, Sign In to add comment