Python Randfacts 库



Python randfacts 库用于生成随机趣味事实。它允许您快速从预定义的类别集中获取随机事实,或在最少的设置下生成随机事实。

安装 randfacts 库

要使用 randfacts 库,您首先需要安装它。这可以使用 Python 的包安装程序 pip 轻松完成。打开您的终端或命令提示符并运行以下命令:

pip install randfacts

导入 randfacts 库

库安装完成后,您可以将 randfacts 导入到您的 Python 脚本中以访问其功能。以下是如何操作:

import randfacts

生成随机事实

randfacts 的主要功能是生成随机事实。您可以使用 get_fact() 方法检索单个随机事实。

示例

import randfacts
fact = randfacts.get_fact()
print(fact)

输出

RUN 1:
Did you know? A crocodile cannot stick its tongue out
RUN 2:
Taipan snakes have 50 times more toxic than a cobra snake

生成多个随机事实

要生成多个随机事实,您可以在循环中多次使用 get_fact()

示例

在以下示例中,我们正在生成并打印十个随机事实:

import randfacts
for _ in range(10):
   fact = randfacts.get_fact()
   print(fact)

输出

The dot that appears over the letter i is called a "tittle."
A Father's Diet Before Conception Plays a Crucial Role in a Child's Health.
The hottest chili in the world is the Tezpur chili pepper
The U.S. Navy has 75 trained dolphins to detect enemy swimmers and underwater mines.
Brazil was once called "United States of Brazil."
The MGM lion roar is trademarked
Parts of the Great Wall of China were made with sticky rice.
The moon is moving away from us by 3.78 cm (1.48 in) a year.
In October 1986, Pepsi paid close to $840 million to Nabisco for the Kentucky Fried Chicken empire
Over 800 languages are spoken in Papua New Guinea.

生成随机事实时的内容过滤

randfacts 库允许您过滤生成的事实内容。默认情况下,get_fact() 会过滤掉明确的内容。但是,您可以通过向函数传递布尔参数来控制此行为。传递 True 会启用过滤器(默认行为),而传递 False 会禁用它。

示例

import randfacts

# Generate a fact with content filtering enabled (default)
print("Fact with content filtering enabled…")
safe_fact = randfacts.get_fact(True)
print(safe_fact)

# Generate a fact with content filtering disabled
print("Fact with content filtering disabled…")
unsafe_fact = randfacts.get_fact(False)
print(unsafe_fact)

输出

Fact with content filtering enabled…
The characters Bert and Ernie on Sesame Street were named after Bert the cop and Ernie the taxi driver in Frank Capra's It's a Wonderful Life.
Fact with content filtering disabled…
In Utah, it is illegal to swear in front of a dead person.

使用命令行运行 randfacts 库

randfacts 也可以直接从命令行执行。

以下是一些您可以使用的命令:

生成一个随机事实

python3 -m randfacts

禁用明确内容过滤生成一个事实

python3 -m randfacts --unsafe

生成安全和不安全事实的混合

python3 -m randfacts –mixed
python_projects_from_basic_to_advanced.htm
广告