我已经为此挣扎了几个小时:
import os, sys, re
print('Type the path to the folder.')
input_path = input()
input_path = os.path.join(input_path)
print('Select the search term')
input_term = input()
search_regex = re.compile(input_term)
all_files = os.listdir(input_path)
for j in range(len(all_files)):
new_path = os.path.join(input_path, all_files[j])
search_regex = re.compile(input_term)
target_file = open(new_path, 'r')
file_content = target_file.read()
file_content_in_list = search_regex.findall(file_content)
print('A grand total of ' + str(len(file_content_in_list)) + ' items were found at ' + str(new_path))
这按预期工作。该代码读取给定文件夹中的所有文件,并检查找到搜索词的次数。但是,当我尝试将代码的不同部分定义为函数时,我只得到错误:
import os, sys, re
def select_folder():
print('Type the path to the folder.')
input_path = input()
input_path = os.path.join(input_path)
def select_all_files():
all_files = os.listdir(input_path)
for j in range(len(all_files)):
search_a_file()
def ask_for_regex():
print('Select the search term')
input_term = input()
search_regex = re.compile(input_term)
def search_a_file():
new_path = os.path.join(input_path, all_files[j])
search_regex = re.compile(input_term)
target_file = open(new_path, 'r')
file_content = target_file.read()
file_content_in_list = search_regex.findall(file_content)
print('A grand total of ' + str(len(file_content_in_list)) + ' items were found at ' + str(new_path))
select_folder(): #Syntax Error here!
ask_for_regex():
select_all_files():
# if i put them like this then everything break down. I guess the variables are forgotten?
select_folder()
ask_for_regex()
select_all_files()
我想这个错误是显而易见的,但我无法理解它......
子衿沉夜
白衣染霜花
相关分类