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
廣告