2 回答

TA贡献1828条经验 获得超3个赞
正如其他人所提到的,您需要对从函数返回值进行一些读取,然后可以在其他区域使用。我重新格式化了你的代码,以显示它可能是什么样子,看看你是否能挑出所做的更改。我重命名了一些函数,以便更好地描述它们的作用。另外,我没有正式测试这段代码,但它应该让你很好地了解你需要采取什么方向。
另外,仍然试图获得声誉点,所以如果它有帮助,请将答案标记为已接受!
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贡献1796条经验 获得超10个赞
下面是一个代码示例,类似于您的原始代码,它以线性方式计算直角三角形的斜边:
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)
添加回答
举报