【问题标题】:Copy selected lines of text from one file to another with command line argument with or without spaces使用带或不带空格的命令行参数将选定的文本行从一个文件复制到另一个文件
【发布时间】:2014-01-29 15:59:13
【问题描述】:

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

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

(例如,假设用户搜索单词“exception”并希望排除单词“abc”,那么代码只会复制其中包含“exception”的行,而不是“abc”)。

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

输入将是:

file.py test.txt(输入文件) test_mod.txt(输出文件) -e abc(排除-e表示的单词)-s exception(搜索-s表示的单词) 现在用户可以选择输入多个排除词和多个搜索词。

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

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)

【问题讨论】:

    标签: python file exception exception-handling argparse


    【解决方案1】:

    一种选择是定义一个-w 参数

    parser.add_argument('-w', action='store_true')
    

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

    要分别控制每个搜索词,除了-e-s 之外,我建议使用--we--ws 等参数名称。理想情况下,单破折号带有单个字母,双破折号带有较长的名称。或使用-E-S。无论argparse 是否执行这样的规则,您的用户都会喜欢清晰简单的规则。无论如何,您最终会得到 4 个单词列表。

    user_input1 = (args.e) 中不需要 ()args.e 已经是一个列表,因为操作是 append。另一种方法是nargs='+',允许您输入-e word1 word2 -s word3 ...+append 也可能有效,但 args.e 可能是列表列表,然后您必须将其展平。

    【讨论】:

    • 你能修改我的程序,让我明白如何存储这2个新集合(仅排除单词,仅包含整个单词)并将它们写入新文件吗?
    • 请帮忙!我被困在这个问题上。
    • 我不确定你卡在哪里了。您可以像处理user_input1 等一样处理新列表。如果您被搜索部分卡住,您可能需要提出一个新问题(例如,如何处理多个输出文件?或如何搜索整个单词? )。提示 - 阅读re \b
    猜你喜欢
    • 2021-12-20
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    相关资源
    最近更新 更多