Python脚本生成随机密码
以下是一个使用Python生成随机密码的脚本: ```python import random import string def generate_password(length): characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(characters) for _ in range(length)) return password password_length = 12 random_password = generate_password(password_length) print("随机密码:", random_password) ``` 这个脚本首先导入了`random`和`string`模块,然后定义了一个名为`generate_password`的函数,该函数接受一个参数`length`,表示要生成的密码的长度。在函数内部,我们创建了一个包含所有大小写字母、数字和标点符号的字符串`characters`,然后使用`random.choice()`函数从`characters`中随机选择字符
Python随机密码生成脚本,去重复字符,可自定义长度和字符集,AI代写的。
importrandomimportstringimporttkinterastkdefgenerate_random_string():try:length=int(entry_length.get())iflength<=0:label_result.config(text="错误:长度必须是正整数")return""exceptValueError:label_result.config(text="错误:请输入一个整数")return""allowed_chars=""ifvar_upper.get():allowed_chars+=string.ascii_uppercaseifvar_lower.get():allowed_chars+=string.ascii_lowercaseifvar_digit.get():allowed_chars+=string.digitsifvar_punct.get():allowed_chars+=string.punctuationifnotallowed_chars:label_result.config(text="错误:请至少选择一种字符集")return""random_string="".join(random.choice(allowed_chars)for_inrange(length))defhas_duplicates(s):returnlen(s)!=len(set(s))defreplace_duplicates(s):new_s=""forchins:ifs.count(ch)>1:new_ch=random.choice(allowed_chars)new_s+=new_chelse:new_s+=chreturnnew_sdefremove_duplicates(s):whilehas_duplicates(s):s=replace_duplicates(s)returnsrs=remove_duplicates(random_string)returnrsdefshow_and_copy_random_string():random_string=generate_random_string()ifrandom_string:label_result.config(text=random_string)window.clipboard_clear()window.clipboard_append(random_string)window=tk.Tk()window.title("随机字符串生成器")window.geometry("400x300")label_welcome=tk.Label(window,text="欢迎使用随机字符串生成器!")label_welcome.pack()label_length=tk.Label(window,text="请输入你想要生成的字符串长度(正整数):")label_length.pack()entry_length=tk.Entry(window)entry_length.pack()var_upper=tk.BooleanVar()var_lower=tk.BooleanVar()var_digit=tk.BooleanVar()var_punct=tk.BooleanVar()check_upper=tk.Checkbutton(window,text="大写字母",variable=var_upper)check_upper.pack()check_lower=tk.Checkbutton(window,text="小写字母",variable=var_lower)check_lower.pack()check_digit=tk.Checkbutton(window,text="数字",variable=var_digit)check_digit.pack()check_punct=tk.Checkbutton(window,text="特殊字符",variable=var_punct)check_punct.pack()button_generate=tk.Button(window,text="一键生成并复制",command=show_and_copy_random_string)button_generate.pack()label_result=tk.Label(window,text="")label_result.pack()window.mainloop()