2 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
正如其他人所提到的,您需要對(duì)從函數(shù)返回值進(jìn)行一些讀取,然后可以在其他區(qū)域使用。我重新格式化了你的代碼,以顯示它可能是什么樣子,看看你是否能挑出所做的更改。我重命名了一些函數(shù),以便更好地描述它們的作用。另外,我沒(méi)有正式測(cè)試這段代碼,但它應(yīng)該讓你很好地了解你需要采取什么方向。
另外,仍然試圖獲得聲譽(yù)點(diǎn),所以如果它有幫助,請(qǐng)將答案標(biāo)記為已接受!
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()

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超10個(gè)贊
下面是一個(gè)代碼示例,類似于您的原始代碼,它以線性方式計(jì)算直角三角形的斜邊:
import math
a = 3
b = 4
c = math.sqrt(a**2 + b**2)
以下是等效的代碼,重新編寫(xiě)以使其更易于組合,更加模塊化:
import math
def hypotenuse(a, b):
return math.sqrt(a**2 + b**2)
c = hypotenuse(3, 4)
添加回答
舉報(bào)