Random word generator- Python

前端 未结 5 1777
长情又很酷
长情又很酷 2020-12-23 20:58

So i\'m basically working on a project where the computer takes a word from a list of words and jumbles it up for the user. there\'s only one problem: I don\'t want to keep

5条回答
  •  难免孤独
    2020-12-23 21:08

    Solution for Python 3

    For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer above by Kyle Kelley.

    import urllib.request
    
    word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
    response = urllib.request.urlopen(word_url)
    long_txt = response.read().decode()
    words = long_txt.splitlines()
    

    Output:

    >>> words
    ['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
     'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
     'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]
    

    And to generate (because it was my objective) a list of 1) upper case only words, 2) only "name like" words, and 3) a sort-of-realistic-but-fun sounding random name:

    import random
    upper_words = [word for word in words if word[0].isupper()]
    name_words  = [word for word in upper_words if not word.isupper()]
    rand_name   = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])
    

    And some random names:

    >>> for n in range(10):
            ' '.join([name_words[random.randint(0,len(name_words))] for i in range(2)])
    
        'Semiramis Sicilian'
        'Julius Genevieve'
        'Rwanda Cohn'
        'Quito Sutherland'
        'Eocene Wheller'
        'Olav Jove'
        'Weldon Pappas'
        'Vienna Leyden'
        'Io Dave'
        'Schwartz Stromberg'
    

提交回复
热议问题