Random Sentence Selection from Text List

  • Share this:

Code introduction


This function randomly selects a specified number of sentences from a given list of texts.


Technology Stack : Lingua (text processing library), random (random number library), datetime (date and time library)

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import datetime

def get_random_sentence(texts, n=1):
    """
    从给定的文本列表中随机获取n个句子。
    
    Args:
    texts (list): 包含句子的列表。
    n (int): 要获取的句子数量,默认为1。
    
    Returns:
    list: 包含随机句子的列表。
    """
    sentences = []
    for _ in range(n):
        sentence = random.choice(texts)
        sentences.append(sentence)
    return sentences

# 示例文本列表
sample_texts = [
    "The quick brown fox jumps over the lazy dog.",
    "Python is an interpreted, high-level, general-purpose programming language.",
    "Lingua is a Python library for processing natural language text.",
    "Natural language processing is a subfield of computer science, artificial intelligence, and computational linguistics.",
    "It involves programming computers to process and analyze large amounts of natural language data."
]

# 使用示例
random_sentences = get_random_sentence(sample_texts, 3)
print(random_sentences)