Python 使用带空格或不带空格的命令行参数将选定的文本行从一个文件复制到另一个文件

Python 使用带空格或不带空格的命令行参数将选定的文本行从一个文件复制到另一个文件,python,file,exception,exception-handling,argparse,Python,File,Exception,Exception Handling,Argparse,我试图用python编写一个程序,在txt文件中搜索用户指定的单词,并将包含该单词的选定行复制到另一个文件中 用户还可以选择排除任何单词 e、 g假设用户搜索单词exception并希望排除单词abc,那么代码将只复制其中包含exception的行,而不复制abc 现在,所有工作都将在命令提示符下完成 投入将是: file.py test.txtinput file test_mod.txtoutput file-e abcexclude word由-e-s exceptions表示搜索词由-s

我试图用python编写一个程序,在txt文件中搜索用户指定的单词,并将包含该单词的选定行复制到另一个文件中

用户还可以选择排除任何单词

e、 g假设用户搜索单词exception并希望排除单词abc,那么代码将只复制其中包含exception的行,而不复制abc

现在,所有工作都将在命令提示符下完成

投入将是:

file.py test.txtinput file test_mod.txtoutput file-e abcexclude word由-e-s exceptions表示搜索词由-s表示现在用户将可以选择输入多个排除词和多个搜索词

我已经使用argparse模块完成了这个程序,并且它可以运行。 我的问题是,当它为排除词和搜索词搜索单词时,它不考虑空格。例如,它会在单词abcExab中找到单词异常。现在有时候我需要这个功能有时候我不需要。这是我现在的代码

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()
我怎样才能在这个程序中包含另外两个参数,比如:-ew和-sw只搜索整个单词,以及-e和-s,即使没有空格也会搜索单词?所以总共有4个参数,-e,-s,-ew,-sw

一个选项是定义-w参数

这将设置args.w布尔值-我们将与-w-e…相同-ew不起作用,因为-e需要一个参数,而-w不需要。但是这个args.w是一个全局开关

为了单独控制每个搜索词,除了-e和-s之外,我建议使用参数名,如-we,-ws。理想情况下,单破折号与单字母连用,双破折号与更长的名称连用。或者使用-E和-S。无论argparse是否强制执行这样的规则,您的用户都会喜欢清晰简单的规则。在任何情况下,你都会得到4个单词列表


您不需要在user\u input1=args.e中输入。args.e已经是一个列表,因为操作是追加的。另一种方法是nargs='+',允许您输入-e word1 word2-s word3..+虽然args.e可能是一个列表列表,但使用append也可能会起作用,然后您必须将其展平。

您能否修改我的程序,以便我了解如何存储这两个新设置“仅排除word”和“仅包含word”作为一个整体,并将它们写入新文件?请帮助!我被困在这里了。我不知道你被困在哪里了。您可以像处理user_input1等一样处理新列表。如果您一直使用搜索部分,您可能需要问一个新问题,例如如何处理多个输出文件?或如何搜索整个单词?。提示-阅读有关re\b的信息。
parser.add_argument('-w', action='store_true')