![](/img/trans.png)
[英]Automate the Boring Stuff With Python randomQuizGenerator Errors
[英]Regex Search Automate Boring Stuff, functions and errors
我已經為此掙扎了幾個小時:
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()
我想這個錯誤很明顯,但我無法理解......
這是一個代碼示例,類似於您的原始代碼,它以線性方式計算直角三角形的斜邊:
import math
a = 3
b = 4
c = math.sqrt(a**2 + b**2)
這是等效的代碼,重新編寫以使其更可組合,更模塊化:
import math
def hypotenuse(a, b):
return math.sqrt(a**2 + b**2)
c = hypotenuse(3, 4)
正如其他人所提到的,您需要對函數的返回值進行一些閱讀,然后可以在其他領域使用這些值。 我重新格式化了您的代碼以顯示它的外觀,看看您是否可以找出進行了哪些更改。 我重命名了一些函數,以便更好地描述它們的作用。 此外,我沒有正式測試這段代碼,但它應該讓您對需要采取的方向有一個很好的了解。
此外,仍在嘗試獲得聲望點,因此如果有幫助,請將答案標記為已接受!
import os
import re
def get_folder_path():
input_path = input('Type the path to the folder: ')
return os.path.join(input_path)
def set_regex():
input_term = input('Type the regex to search for: ')
return re.compile(input_term)
def search_for_files():
path = get_folder_path()
search_regex = set_regex()
file_list = os.listdir(path)
count = 0
for file in file_list:
with open(file, 'r') as f:
file_content = f.read()
match = re.search(search_regex, file_content)
if match:
count += 1
print('A grand total of ' + str(count) + ' items were found at ' + str(path))
search_for_files()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.