import random
def extract_digits(text):
return [int(char) for char in text if char.isdigit()]
def random_digits_from_file(file_path, num_digits):
with open(file_path, 'r') as file:
text = file.read()
digits = extract_digits(text)
if len(digits) < num_digits:
raise ValueError("文件中的数字不足以随机选择指定数量的数字。")
return random.sample(digits, num_digits)
# 替换为您的文件路径
file_path = "c:\pi.txt"
# 从文件中随机选择5个数字
try:
random_numbers = random_digits_from_file(file_path, 5)
print(random_numbers)
except FileNotFoundError:
print("文件未找到。请检查文件路径是否正确。")
except ValueError as e:
print(e)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交