Random word generator python

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.

This is a simple python package to generate random english words

License

vaibhavsingh97/random-word

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.

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

This is a simple python package to generate random English words. If you need help after reading the below, please find me on Twitter at @vaibhavsingh97.

If you love the package, please 🌟 the repo.

You should be able to install using easy_install or pip in the usual ways:

$ easy_install random-word $ pip install random-word

Or clone this repository and run:

Or place the random-word folder that you downloaded somewhere where your scripts can access it.

👋 This package will now, by default, fetch the random word from local database

from random_word import RandomWords r = RandomWords() # Return a single random word r.get_random_word()

Different services are available as a part of the random word package, which fetches random words from various API providers. Please check the Services section for more details.

Assuming that you have Python and pipenv installed, set up your environment and install the required dependencies like this instead of the pip install random-word defined above:

$ git clone https://github.com/vaibhavsingh97/random-word.git $ cd random-word $ make init

Add API Key in random_word directory defining API Key in config.yml . If you don’t have an API key, then request your API key [here][wornikWebsiteLink]

Читайте также:  Is system class in java is final

To check your desired changes, you can install your package locally.

You can report the bugs at the issue tracker

Built with ♥ by Vaibhav Singh(@vaibhavsingh97) under MIT License

About

This is a simple python package to generate random english words

Источник

Random word generator python

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.

Читайте также:  Javascript void 0 gridrunaction

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.

Источник

Random Word Generator

Which other python packages are needed to be installed?

What this library does?

It helps us to generate random words i.e random noise in text data which is helpful in many text augmentation based tasks, NER, etc.

Читайте также:  Факториал заданного числа python

Which methods are available currently in this library?

Method Args Description
.generate() None This will return a randomly generated word
.getList(num_of_words) num_of_words This will return list of random words

Setting to look out before generating random words

Basic

from RandomWordGenerator import RandomWord # Creating a random word object rw = RandomWord(max_word_size, constant_word_size=True, include_digits=False, special_chars=r"@_!#$%^&*()<>?/\|> 
Args Data Type Default Description
max_word_size int 10 Represents maximum length of randomly generated word
constant_word_size bool True Represents word length of
randomly generated word
include_digits bool False Represents whether or not to include digits in generated words
special_chars regex/string r"@_!#$%^&*()<>?/\\
|>

Represents a regex string of all specials character you want to include in generated words
include_special_chars bool False Represents inclusion of special characters in generated words

How to get started with this library?

from RandomWordGenerator import RandomWord rw = RandomWord(max_word_size=5) print(rw.generate()) 
Output will be some random word like > hdsjq 
from RandomWordGenerator import RandomWord rw = RandomWord(max_word_size=5, constant_word_size=False) print(rw.generate()) 
Output will be some random word like > gw 
from RandomWordGenerator import RandomWord rw = RandomWord(max_word_size=5, constant_word_size=True, special_chars=r"@#$%.*", include_special_chars=True) print(rw.generate()) 
Output will be some random word like > gsd$ 
from RandomWordGenerator import RandomWord rw = RandomWord(max_word_size=5, constant_word_size=False) print(rw.getList(num_of_random_words=3)) 
Output will be some random word like > ['adjse', 'qytqw', ' klsdf', 'ywete', 'klljs'] 

Application

  • In cases where we need to add random noise in text
  • Name Entity Relation extraction based tasks
  • Text Data Augmentation based tasks

Author

I will be happy to connect with you guys!!

Any suggestions are most welcome.

Источник

random-word

This is a simple python package to generate random English words. If you need help after reading the below, please find me on Twitter at @vaibhavsingh97.

If you love the package, please :star2: the repo.

Installation

You should be able to install using easy_install or pip in the usual ways:

$ easy_install random-word $ pip install random-word

Or clone this repository and run:

Or place the random-word folder that you downloaded somewhere where your scripts can access it.

Basic Usage

👋 This package will now, by default, fetch the random word from local database

 Different services are available as a part of the random word package, which fetches random words from various API providers. Please check the Services section for more details.

Services

Development

Assuming that you have Python and pipenv installed, set up your environment and install the required dependencies like this instead of the pip install random-word defined above:

$ git clone https://github.com/vaibhavsingh97/random-word.git $  random-word $ make init

Add API Key in random_word directory defining API Key in config.yml . If you don't have an API key, then request your API key [here][wornikWebsiteLink]

To check your desired changes, you can install your package locally.

Issues

You can report the bugs at the issue tracker

License

Built with ♥ by Vaibhav Singh(@vaibhavsingh97) under MIT License

Источник

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