我正在嘗試在python中編寫一個程序,該程序在txt文件中搜索用戶指定的單詞,並將包含該單詞的選定行復制到另一個文件中。將選定的行從一個文件複製到另一個文件
另外,用戶可以選擇排除任何單詞。 (例如,假設用戶搜索單詞「異常」並希望排除單詞「abc」,那麼代碼將只複製其中具有「異常」但不包含「abc」的行)。
現在所有的工作都將在命令提示符下完成。
輸入將是:
file.py test.txt(input file) test_mod.txt(output file) -e abc(exclude word denoted by -e)-s exception(search word denoted by -s)
現在,用戶將有一個選項,輸入多個排除詞和多個搜索詞。
現在爲止我已經實現了輸入格式爲:
file.py test.txt test_mod.txt abc exception".
這不包括單詞「ABC」,然後搜索「例外」。
但我不知道如何:
- 包括多個搜索詞,並排除的話
- 如何通過-e和-s來表示他們。我已經看到了argparse和getopt教程。但沒有關於這個特定主題的教程。
請有人可以幫我修改我的代碼或寫一個新的?
這裏是我的代碼,截至目前:
#/Python33
import sys
import os
def main(): #main method
try:
f1 = open(sys.argv[1], 'r') #takes the first input file in command line
found = False
user_input1 = (sys.argv[3]) #takes the word which is to be excluded.
user_input2 = (sys.argv[4]) #takes the word which is to be included.
if sys.argv[1] == sys.argv[2]:
f1.close()
sys.exit('\nERROR!!\nThe two file names cannot be the same.')
if sys.argv[3] != sys.argv[4]:
for line in f1:
if user_input1 in line or user_input2 in line:
f2 = open(sys.argv[2], 'a')
if user_input1 in line:
if user_input2 in line:
pass
elif user_input2 in line:
f2.write(line)
found = True
f2.close()
if not found:
print("ERROR: The Word couldn't be found.")
f1.close()
if sys.argv[3] == sys.argv[4]:
f1.close()
sys.exit('\nERROR!!\nThe word to be excluded and the word to be included cannot be the same.')
except IOError:
print('\nIO error or wrong file name.')
except IndexError:
print('\nYou must enter 5 parameters.') #prevents less than 5 inputs which is mandatory
except SystemExit as e: #Exception handles sys.exit()
sys.exit(e)
if __name__ == '__main__':
main()
感謝的人。這真的幫助我理解邏輯。但我是python的新手,所以我仍然遇到一些問題。每當我運行它時,它都會使用-s指定的文字複製文件,但不排除由-e指定的文字。我究竟做錯了什麼?因此,這裏是我現在的代碼: #/ Python33
#takes a text file, finds a word and writes that line containing that word but not a 2nd word specified by the user. So if both of them are there, that line is not printed
import sys
import os
import argparse
def main(): #main method
try:
parser = argparse.ArgumentParser(description='Copies selected lines from files')
parser.add_argument('input_file')
parser.add_argument('output_file')
parser.add_argument('-e',action="append")
parser.add_argument('-s',action="append")
args = parser.parse_args('test.txt, test_mod.txt, -e , -s exception'.split())
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=[]):
with open(output_file, 'w') as fo:
with open(input_file, 'r') as fi:
for line in fi:
inclusion_words_in_line = map(lambda x: x in line, inclusion_list)
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):
fo.write(line)
if user_input1 != user_input2 :
include_exclude('test.txt', 'test_mod.txt', user_input1, user_input2);
print("hello")
if user_input1 == user_input2 :
sys.exit('\nERROR!!\nThe word to be excluded and the word to be included cannot be the same.')
except IOError:
print('\nIO error or wrong file name.')
except IndexError:
print('\nYou must enter 5 parameters.')
except SystemExit as e:
sys.exit(e)
if __name__ == '__main__':
main()
我不得不清理縮進一點,但你的代碼對我來說工作得很好(包括和不包括)。你忘了把'parser.parse_args('test ...)'改回'parser.parse_args()'並且同樣改變'test.txt'和'test_mod.txt'? – kalhartt