python - 随机 url 生成器,但确保结果是唯一的
问题描述
我发现自己在网上寻找一个模仿 twitch 剪辑随机 URL 模式的 URL/字符串生成器。有关我的意思的示例,请参见此处。我碰巧找到了readable-url但可惜它是用于npm
. 所以...为了让 Python 用户可以使用它,我正在为我们制作一个!实际上我已经做到了,它现在在我的 github 中。
我的困境是我想确保所有字符串对于每个生成的响应都是唯一的。完整代码如下。
from random import choice, sample
vowels = {'a', 'e', 'i', 'o', 'u'}
with open("words/adjectives.txt") as adjs_file:
adjectives = adjs_file.read().split()
with open("words/nouns.txt") as words_file:
nouns = words_file.read().split()
class SentenceURL:
def __init__(self, word_count = 3, capitalize = True, seperator = ''):
self.word_count = word_count
self.capitalize = capitalize
self.seperator = seperator
def generate():
"""Generates readable URLs like Twitch's clips"""
if self.word_count < 2:
raise ValueError('Minimum value expected: 2')
elif self.word_count > 10:
raise ValueError('Maximum value expected: 10')
noun = choice(nouns)
word_list = []
if self.word_count > 3:
if noun in vowels:
word_list = ['an']
else:
word_list = [choice(('a', 'the'))]
word_list.extend(sample(adjectives, k = self.word_count-1))
if self.word_count > 4:
word_list.insert(2, 'and')
word_list.append(noun)
if self.capitalize:
word_list = map(str.title, word_list)
return self.seperator.join(word_list)
所以我最初的想法是只保留一组以前使用过的字符串,看看新的字符串是否在集合中,如果它生成另一个,这很容易实现,但似乎效率很低。我还有什么其他选择?谢谢!
解决方案
推荐阅读
- c++ - constexpr 构造函数不被称为隐式类型转换的 constexpr
- azure-ad-b2c - 收到的身份验证响应没有预期的 accessToken
- laravel - Laravel 显示“FPDF 错误:尚未添加页面”
- python - 如何使用 Qt 制作 cookie?
- c++ - 什么是调用 std::forward 的正确方法
不止一次? - python - 如何在游戏中添加简单图形以在屏幕上添加滚动文本?
- android - RuntimeException:无法启动活动错误膨胀类 ImageView 和 ImageButton
- laravel-excel - Laravel excel 导出队列和MultipleSheet
- python - 如何正确编写从单独的 json 文件中读取密钥的 python 函数
- highcharts - 我如何使用 highcharts 做到这一点,叠加两个系列与 yAixs 共享