2014-01-23 3 views
0

txt 파일에서 사용자가 지정한 단어를 검색하고 해당 단어가 들어있는 선택한 줄을 복사하는 python으로 프로그램을 작성하려고합니다. 다른 파일.텍스트 파일에서 단어를 검색하고 다른 단어로 복사하는 중 단어의 대소 문자를 무시하는 방법

또한 사용자는 단어를 제외 할 수있는 옵션을 갖게됩니다.

(예 : 사용자가 "예외"라는 단어를 검색하고 "abc"라는 단어를 제외한다고 가정하면 코드는 "예외"가 있지만 "abc"가 아닌 행만 복사합니다).

이제 모든 작업이 명령 프롬프트에서 수행됩니다.

입력이 될 것이다 :

file.py의 TEST.TXT (입력 파일) test_mod.txt (파일 출력) -e는 ABC (-e로 표시된 단어를 제외)로 표시 예외 (검색어를 -s - s) 이제 사용자는 여러 개의 제외 단어와 여러 개의 검색어를 입력 할 수있는 옵션을 갖게됩니다.

나는 argparse 모듈을 사용하여 프로그램을 수행했고 실행했다. 내 문제는 소문자 단어 만 검색 또는 제외한다는 것입니다. 즉, 검색 단어로 "예외"를 입력하면 "예외"또는 "예외"가 없습니다. 이 문제를 어떻게 해결합니까? 검색 및 제외 단어 모두에서 대소 문자를 무시하고 싶습니다.

import sys 
import os 
import argparse 
import tempfile 
import re 

def main(): #main method 

try: 

    parser = argparse.ArgumentParser(description='Copies selected lines from files') #Defining the parser 
    parser.add_argument('input_file') #Adds the command line arguments to be given 
    parser.add_argument('output_file') 
    parser.add_argument('-e',action="append") 
    parser.add_argument('-s',action="append") 
    args = parser.parse_args() #Parses the Arguments 
    user_input1 = (args.e) #takes the word which is to be excluded. 
    user_input2 = (args.s) #takes the word which is to be included. 

    def include_exclude(input_file, output_file, exclusion_list=[], inclusion_list=[]): #Function which actually does the file writing and also handles exceptions 
     if input_file == output_file: 
      sys.exit("ERROR! Two file names cannot be the same.") 
     else: 
      try: 
       found_s = False #These 3 boolean variables will be used later to handle different exceptions. 
       found_e = False 
       found_e1 = True 
       with open(output_file, 'w') as fo: #opens the output file 
        with open(input_file, 'r') as fi: #opens the input file 
         for line in fi:  #reads all the line in the input file 
          if user_input2 != None: 


           inclusion_words_in_line = map(lambda x: x in line, inclusion_list)#Mapping the inclusion and the exclusion list in a new list in the namespace 
           if user_input1 != None and user_input2 != None:     #This list is defined as a single variable as condition operators cannot be applied to lists 
            exclusion_words_in_line = map(lambda x: x in line, exclusion_list) 
            if any(inclusion_words_in_line) and not any(exclusion_words_in_line): #Main argument which includes the search word and excludes the exclusion words 

             fo.write(line) #writes in the output file 
             found_s = True 

           elif user_input1 == None and user_input2 != None: #This portion executes if no exclude word is given,only the search word  
            if any(inclusion_words_in_line): 
             fo.write(line) 
             found_e = True 
             found_s = True 
             found_e1 = False 

         if user_input2 == None and user_input1 != None:  #No search word entered 

          print("No search word entered.") 

         if not found_s and found_e:    #If the search word is not found       
          print("The search word couldn't be found.") 
          fo.close() 
          os.remove(output_file) 

         elif not found_e and not found_s:  #If both are not found       
          print("\nNOTE: \nCopy error.") 
          fo.close() 
          os.remove(output_file) 

         elif not found_e1:    #If only the search word is entered        
          print("\nNOTE: \nThe exclusion word was not entered! \nWriting only the lines containing search words") 

      except IOError: 
       print("IO error or wrong file name.") 
       fo.close() 
       os.remove(output_file) 
    if user_input1 != user_input2 : #this part prevents the output file creation if someone inputs 2 same words creating an anomaly. 
     include_exclude(args.input_file, args.output_file, user_input1, user_input2); 


    if user_input1 == user_input2 : #This part prevents the program from running further if both of the words are same 
     sys.exit('\nERROR!!\nThe word to be excluded and the word to be included cannot be the same.') 


except SystemExit as e:      #Exception handles sys.exit() 
     sys.exit(e) 



if __name__ == '__main__': 
    main() 
+0

이것은 학습을위한 작업입니까? 또는 실생활 코드? –

+0

예. 실생활 코드. – sagarnildass

답변

3

이 작업을 수행하는 일반적인 방법은 모든 점에서 비교 한 경우를 선택하고 확인하는 것입니다 : 귀하의 경우를 들어

if word.lower() == "exception": 

을이 같이 볼 수 있었다 여기에 지금과 같은 내 코드입니다 :

이 검색 엔진을 구축하려는 시도처럼 보인다
inclusion_words_in_line = map(lambda x: x in line.lower(), 
           inclusion_list) 
+0

많은 감사합니다! 그것은 작동했습니다 ... – sagarnildass

0

, 당신은 pylucene

같은 라이브러리를 사용하여이를 달성 할 수 0

당신은 다음과 같은 쿼리를 실행할 수 있습니다 :

+include -exclude 

잘, 그리고 물론 많은 더 많은, 그것은 학습 곡선 가치가 않을 수 있습니다.

+0

Ok. 감사....:) – sagarnildass

관련 문제