目标是从多个子文件夹中的 .txt 文件中随机选择 10 个任务。这些任务可能包含在不同的文件中,并且每个文件中可能有多个任务。需要确保每次选择的任务都是不同的,并且能够在下次执行时被标记或删除,以避免重复选择。
-
解决方案
为了解决这个问题,可以使用 Python 中的随机模块和 os 模块。随机模块提供了生成随机数和随机样本的函数,而 os 模块提供了对文件和文件夹的访问。首先,可以编写一个生成器函数来遍历所有子文件夹中的 .txt 文件并生成其中的行。这个函数接受一个根文件夹路径和一个排除集合作为参数。排除集合包含已经选择的行,以便在下次选择时避免重复。
接下来,可以编写一个函数来使用随机模块从生成器函数中生成的行的迭代器中随机选择指定数量的行。这个函数可以返回一个列表,包含所选的行。
最后,可以创建一个包装函数来调用上述两个函数并管理已选择的行的集合。这个包装函数可以返回单个样本或多个样本,具体取决于传入的参数。
下面是代码示例:
import random
import os
def lines_generator(base_folder, exclude=None):
for dirpath, dirs, files in os.walk(base_folder):
http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
for filename in files:
if filename.endswith(".txt"):
fullPath = os.path.join(dirpath, filename)
with open(fullPath) as f:
for line in f:
cleanLine = line.strip()
if exclude is None or cleanLine not in exclude:
yield cleanLine
def random_sample(n, items):
results = []
for i, v in enumerate(items):
r = random.randint(0, i)
if r < n:
if i < n:
results.insert(r, v) # add first n items in random order
else:
results[r] = v # at a decreasing rate, replace random items
if len(results) < n:
raise ValueError("Sample larger than population.")
return results
_seen = set()
def get_sample(n, count = None):
base_folder = r"C:\Tasks"
if count is None:
sample = random_sample(n, lines_generator(base_folder, _seen))
_seen.update(sample)
return sample
else:
sample = random_sample(count * n, lines_generator(base_folder, _seen))
_seen.update(sample)
return [sample[i * n:(i + 1) * n] for i in range(count)]
def main():
s1 = get_sample(10)
print("Sample1:", *s1, sep="\n")
s2, s3 = get_sample(10,2) # get two samples with only one read of the files
print("\nSample2:", *s2, sep="\n")
print("\nSample3:", *s3, sep="\n")
s4 = get_sample(5000) # this will probably raise a ValueError!
if __name__ == "__main__":
main()
这个解决方案可以在所有子文件夹中的 .txt 文件中随机选择 10 个任务,并且能够在下次执行时标记或删除已选择的 任务,以避免重复选择。它使用随机模块和 os 模块,并通过生成器函数和包装函数来实现。