Home > database >  (Python3) - Random number inserted at the end of only 1 word in a string of many words
(Python3) - Random number inserted at the end of only 1 word in a string of many words

Time:10-19

I am trying to make a random word/phrase generator that is like the one that bitwarden has (in python3). But the issue I am running into and need some help with is the addition of 1 number at the end of 1 of the words that is shown.

Something like this Referee-Outrank-Cymbal-Cupping-Cresting-Fiber7-Expensive-Myth-Unveiling-Grasp-Badland-Epiphany-Simplify-Munchkin-Pastrami-Spiffy-Gladly-Skeptic-Retouch-Buckskin

What is very important here is that the number is "random" and the word it is attached to is "random".

Code I have written so far:

Word list I am using is https://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain but without ' in any of the words.

#pycryptodome==3.15.0

from Crypto.Random import random
import beaupy
import os



def clear():
    os.system('clear||cls')


def main():
    while True:
        try:
            number = int(beaupy.prompt("How many words?: "))
        except ValueError as e:
            print(f'Oops! Something went wrong.\nError: {e}\n\n')
            input('Press "enter" to continue...')
            clear()
            continue
            

        if number > 20 or number < 3:
            print("20 words is the maximum number of words you can use. And 5 words is the minimum.\n\n")
            input('Press "enter" to continue...')
            clear()
        else:
            break


    cwd = os.getcwd()
    word_path = f"{cwd}/words.txt"
    with open(word_path, 'r') as fh:
        words = fh.read().lower()
    word_list = words.splitlines() #list of words

    sep = beaupy.prompt('Line separator? (leave empty for default "-"): ')
    if sep == '' or sep == ',':
        sep = '-'


    #Returns True or False. Basically Yes or No?
    if beaupy.confirm("Capitalize?"):
        """Make list of words with the first letter capitalized."""
        c_lst = []
        for i in word_list:
            c_lst.append(i.title())


        capital_words = f'{sep}'.join(random.choice(c_lst) for _ in range(number))
    else:
        default_words = f'{sep}'.join(random.choice(word_list) for _ in range(number))



        if beaupy.confirm("Number?"):
            rn_num = random.randint(0, 9) # <-- Get a random number to be used with only 1 of the words defined in capital_words or default_words below.
            #I don't know what to do here... but I need to have a version with the number and one without. (default)


            
    



if __name__ == '__main__':
    clear()
    main()





I am not exactly familiar with string manipulation and searching for answers online just isn't giving me any help with the very specific thing I'm trying to do. All I want is for 1 word in the resulting string to have a "random" number attached to it.

I don't know if I need to re order my code and have it be done a different way. I am having such a headache with this. Any help would be great.



Edit#1 Additional and unrelated note, If anyone knows of a better word list to use, please let me know!

CodePudding user response:

If I am understanding correctly, here is a solution:

#Returns True or False. Basically Yes or No?
    capital_words = ''
    default_words = ''
    if beaupy.confirm("Capitalize?"):
        """Make list of words with the first letter capitalized."""
        c_lst = []
        for i in word_list:
            c_lst.append(i.title())


        capital_words = f'{sep}'.join(random.choice(c_lst) for _ in range(number))
    else:
        default_words = f'{sep}'.join(random.choice(word_list) for _ in range(number))



    if beaupy.confirm("Number?"):
        rn_num = random.randint(0, 9) # <-- Get a random number to be used with only 1 of the words defined in capital_words or default_words below.
        #I don't know what to do here... but I need to have a version with the number and one without. (default)
        word_index = random.randint(0, number - 1) # Get random index that is in the word list
        if default_words != '':
            word_with_number = default_words.split(sep)
        else:
            word_with_number = capital_words.split(sep)
        word_with_number[word_index] = word_with_number[word_index]   str(rn_num)
        word_with_number = sep.join(word_with_number)
        print(word_with_number)

    if default_words != '':
        print(default_words)
    else:
        print(capital_words)

OUTPUT:

detroit-elide-windbag-purge-tort-mortician-codex7-annex-fairy-suntanning
detroit-elide-windbag-purge-tort-mortician-codex-annex-fairy-suntanning

CodePudding user response:


With some help from AnonymousFrog. I was able to get my code working.

The following is the now working code.

from Crypto.Random import random
import beaupy
import os



def clear():
    os.system('clear||cls')


def main():
    while True:
        try:
            number = int(beaupy.prompt("How many words?: "))
        except ValueError as e:
            print(f'Oops! Something went wrong.\nError: {e}\n\n')
            input('Press "enter" to continue...')
            clear()
            continue
            

        if number > 20 or number < 3:
            print("20 words is the maximum number of words you can use. And 5 words is the minimum.\n\n")
            input('Press "enter" to continue...')
            clear()
        else:
            break


    cwd = os.getcwd()
    word_path = f"{cwd}/words.txt"
    with open(word_path, 'r') as fh:
        words = fh.read().lower()
    word_list = words.splitlines() #list of words

    sep = beaupy.prompt('Line separator? (leave empty for default "-"): ')
    if sep == '' or sep == ',':
        sep = '-'


    #Returns True or False. Basically Yes or No?
    capital_words = ''
    default_words = ''
    if beaupy.confirm("Capitalize?"):
        """Make list of words with the first letter capitalized."""
        c_lst = []
        for i in word_list:
            if len(i) < 3 or len(i) > 9:
                pass
            else:
                c_lst.append(i.title())

        cap = True
        capital_words = f'{sep}'.join(random.choice(c_lst) for _ in range(number))
    else:
        cap = False
        default_words = f'{sep}'.join(random.choice(word_list) for _ in range(number))


    if beaupy.confirm("Number?"):
        num = True
        rn_num = random.randint(0, 9) # <-- Get a random number to be used with only 1 of the words defined in capital_words or default_words below.
        word_index = random.randint(0, number - 1) # Get random index that is in the word list

        if default_words != '':
            word_with_number = default_words.split(sep)
        else:
            word_with_number = capital_words.split(sep)

        word_with_number[word_index] = word_with_number[word_index]   str(rn_num)
        word_with_number = sep.join(word_with_number)
    else:
        num = False
        

    if cap == True and num == False:
        print(capital_words)
    if cap == False and num == False:
        print(default_words)
    if num == True:
        print(word_with_number)

Thanks for the help! (if anyone knows of a better word list to use, feel free to let me know)

  • Related