首页 > 解决方案 > 随机 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)

所以我最初的想法是只保留一组以前使用过的字符串,看看新的字符串是否在集合中,如果它生成另一个,这很容易实现,但似乎效率很低。我还有什么其他选择?谢谢!

标签: python

解决方案


推荐阅读