Рандомные фразы в питоне

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Generate random text based on template

ivanenko/python_text_randomizer

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Читайте также:  Python telegram bot регистрация пользователя

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Generate random text based on template

from text_randomizer import TextRandomizer template = ' fox [lazy|crazy] dog' text_rnd = TextRandomizer(template) print(text_rnd.get_text())

You will get random text like ‘Red fox dig under crazy lazy dog’.

Template is a usual short or long text with special randomize commands:

  • ‘Synonyms’ command — — insert one of the variants to the result string
  • If you want to omit text — use ’empty’ variant —
  • Mixin command = [ text 1 | text 2 | text 3] — will mix this variants randomly
  • You can use separator in mixin — [+,+text 1|text2 ] — you will get text2,text1. Separator can by any symbol or set of symbols: [+==+ a|b] — a==b or b==a
  • If you want to get spesial symbol in your result (», ‘[‘, ‘]’, ‘|’, ‘+’) — use backslash for it — , [, ], |, +
  • All this commands can be mixed and nested in all combinations: ‘start > or [a1||a3| [aa1|aa2|aa3]]’
  • You can use special predefined random functions in templates — . Result will be = ‘random integer = 4, uuid = 8ae6bdf4-d321-40f6-8c3c-81d20b158acb, now = 2017-08-01’ You can define your own randomization functions and use it in templates. Read about functions further.

Pass template string to TextRandomizer constructor. It will be parsed at once. After creating randomizer object, you can use its get_text() method.

This behaviour can be changed — if you pass parse=False parameter to constructor: TextRandomizer(templ_str, parse=False) — template will not be parsed before you run TextRandomizer.parse() method. Only after this method you can use get_text() method. This can be usefull is several cases. Lets see some examples.

from text_randomizer import TextRandomizer # parse template at once text_rnd1 = TextRandomizer('randomize please') for i in range(0,10): print(text_rnd1.get_text()) # Do not parse template. Parse when needed. This can save you time and memory text_rnd2 = TextRandomizer('randomize please $YOUR_FUNC(5)', parse=False) # you can register your own randomization functions before parsing # run parse() before get_text() call. Otherwise you will get exception text_rnd2.parse() for i in range(0,10): print(text_rnd2.get_text())

You can get number of all possible variants by calling TextRandomizer.variants_number() method. But if you use randomize functions — this value will be imprecise.

For example — ‘start end’ — will give you 2 variants. And ‘start $UUID end’ will give you infinite variants.

Next example shows how to register your own function. Do it before parse() call

text_rnd = TextRandomizer('$YOUR_FUNC1(5, 10) and $FUNC2(param1, param2)', parse=False) # use simple callable for function text_rnd.add_function('FUNC2', lambda p1, p2: '<> and <>'.format(p1, p2)) # use dictionary for more complicated cases. text_rnd.add_function('YOUR_FUNC1', 'callable': lambda x, y: randint(x,y), 'coerce': int>) text_rnd.parse() print(text_rnd.get_text())

About

Generate random text based on template

Источник

Рандомные фразы в питоне

Last updated: Feb 22, 2023
Reading time · 4 min

banner

# Table of Contents

# Generate random words in Python

To generate a random word from the file system:

  1. Open a file in reading mode.
  2. Use the str.splitlines() or str.split() method to split the contents of the file into a list.
  3. Use the random.choice() method to pick as many random words from the list as necessary.
Copied!
import random def get_list_of_words(path): with open(path, 'r', encoding='utf-8') as f: return f.read().splitlines() words = get_list_of_words('/usr/share/dict/words') print(words) random_word = random.choice(words) print(random_word) # 👉️ sales

generate random words

If you’d rather generate random words from a remote database (HTTP request), click on the following subheading:

The code sample generates random words from a file on the local file system.

If you are on Linux or macOS, you can use the /usr/share/dict/words/ file.

If you are on Windows, you can use this MIT word list.

Open the link, right-click on the page and click «Save as», then save the .txt file right next to your Python script.

We used the with statement to open the file in reading mode.

The statement automatically takes care of closing the file for us.

Copied!
import random import requests def get_list_of_words(path): with open(path, 'r', encoding='utf-8') as f: return f.read().splitlines() words = get_list_of_words('/usr/share/dict/words') print(words) random_word = random.choice(words) print(random_word) # 👉️ sales

Make sure to update the path if you aren’t on macOS or Linux.

We used the file.read() method to read the contents of the file into a string.

# Splitting by newlines or splitting by spaces

The str.splitlines method splits the string on newline characters and returns a list containing the lines in the string.

Copied!
multiline_str = """\ bobby hadz com""" lines = multiline_str.splitlines() print(lines) # 👉️ ['bobby', 'hadz', 'com']

splitting by newlines or splitting by spaces

If the words in your file are separated by spaces, use the str.split() method instead.

Copied!
string = "bobby hadz . com" lines = string.split() print(lines) # 👉️ ['bobby', 'hadz', '.', 'com']

The str.split() method splits the string into a list of substrings using a delimiter.

When no separator is passed to the str.split() method, it splits the input string on one or more whitespace characters.

# Picking a random word from the list

If you need to pick a random word from the list, use the random.choice() method.

Copied!
import random def get_list_of_words(path): with open(path, 'r', encoding='utf-8') as f: return f.read().splitlines() words = get_list_of_words('/usr/share/dict/words') print(words) random_word = random.choice(words) print(random_word) # 👉️ unbreakable

picking random word from list

The random.choice method takes a sequence and returns a random element from the non-empty sequence.

# Picking N random words from the list

If you need to pick N random words from the list, use a list comprehension.

Copied!
import random def get_list_of_words(path): with open(path, 'r', encoding='utf-8') as f: return f.read().splitlines() words = get_list_of_words('/usr/share/dict/words') print(words) n_random_words = [ random.choice(words) for _ in range(3) ] # 👇️ ['computers', 'praiseworthiness', 'shareholders'] print(n_random_words)

picking n random words from list

We used a list comprehension to iterate over a range object.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

The range class is commonly used for looping a specific number of times.

On each iteration, we call the random.choice() method to pick a random word and return the result.

# Generate random words from a remote database (HTTP request)

To generate random words from a remote database:

  1. Make an HTTP request to a database that stores a word list.
  2. Use the random.choice() method to pick a random word from the list.
  3. Optionally, use a list comprehension to pick N random words from the list.
Copied!
import random import requests def get_list_of_words(): response = requests.get( 'https://www.mit.edu/~ecprice/wordlist.10000', timeout=10 ) string_of_words = response.content.decode('utf-8') list_of_words = string_of_words.splitlines() return list_of_words words = get_list_of_words() print(words) random_word = random.choice(words) print(random_word) # 👉️ zoo

If you don’t have the requests module installed, install it by running the following command.

Copied!
# 👇️ in a virtual environment or using Python 2 pip install requests # 👇️ for python 3 (could also be pip3.10 depending on your version) pip3 install requests

You can open the MIT word list in your browser to view the contents.

The list contains 10,000 words with each word on a separate line.

We used the bytes.decode() method to convert the bytes object to a string.

The bytes.decode method returns a string decoded from the given bytes. The default encoding is utf-8 .

The words are on separate lines, so we used the str.splitlines() method to split the string into a list of words.

If your database responds with a long string containing space-separated words, use the str.split() method instead.

Copied!
string = "bobby hadz . com" lines = string.split() print(lines) # 👉️ ['bobby', 'hadz', '.', 'com']

# Picking a random word from the list

If you need to pick a random word from the list, use the random.choice() method.

Copied!
import random import requests def get_list_of_words(): response = requests.get( 'https://www.mit.edu/~ecprice/wordlist.10000', timeout=10 ) string_of_words = response.content.decode('utf-8') list_of_words = string_of_words.splitlines() return list_of_words words = get_list_of_words() print(words) random_word = random.choice(words) print(random_word) # 👉️ global

# Picking N random words from the list

If you need to pick N random words from the list, use a list comprehension.

Copied!
import random import requests def get_list_of_words(): response = requests.get( 'https://www.mit.edu/~ecprice/wordlist.10000', timeout=10 ) string_of_words = response.content.decode('utf-8') list_of_words = string_of_words.splitlines() return list_of_words words = get_list_of_words() print(words) n_random_words = [ random.choice(words) for _ in range(3) ] # 👇️ ['clerk', 'trust', 'tr'] print(n_random_words)

The list comprehension iterates over a range object of length N and calls the random.choice() method to pick a random word on each iteration.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to generate a random string in Python

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

Python is a ​powerful language that allows programmers to perform various tasks using built-in libraries. A random string, for example, can be generated using the built-in libraries. Two libraries are imported for this:

import string import random 

Using this random module, different random strings can be generated.

random.choice() is used to generate strings in which characters may repeat, while random.sample() is used for non-repeating characters.

Method Description
string.ascii_uppercase Returns a string with uppercase characters
string.ascii_lowercase Returns a string with lowercase characters
string.ascii_letters Returns a string with both lowercase and uppercase characters
string.digits Returns a string with numeric characters
string.punctuation Returns a string with punctuation characters

Code

import random
import string
# printing lowercase
letters = string.ascii_lowercase
print ( ''.join(random.choice(letters) for i in range(10)) )
# printing uppercase
letters = string.ascii_uppercase
print ( ''.join(random.choice(letters) for i in range(10)) )
# printing letters
letters = string.ascii_letters
print ( ''.join(random.choice(letters) for i in range(10)) )
# printing digits
letters = string.digits
print ( ''.join(random.choice(letters) for i in range(10)) )
# printing punctuation
letters = string.punctuation
print ( ''.join(random.choice(letters) for i in range(10)) )

Learn in-demand tech skills in half the time

Источник

Оцените статью