用python生成随机的句子:nltk库的使用方法

在测试过程中有时需要生成一些随机的句子,这些句子中包含正常的单词,而不是随机的字母组成的无意义单词,这时就用到了nltk库

import nltk
from nltk.corpus import words


def generate_sentence(length):
    word_list = words.words()
    sentence = random.sample(word_list, length)
    return ' '.join(sentence).capitalize() + '.'

1、words.words()

这一步是使用 NLTK(Natural Language Toolkit) 提供的 words.words(),它会从 nltk.corpus.words 中获取一个包含大量英文单词的列表。(如何在本地安装nltk的words库,可以参考我的上一篇文章CSDN

2、random.sample(word_list, length)

random.sample() 用于无重复地从 word_list 里随机抽取 length 个单词。
这样确保返回的句子中的单词不会重复。

3、' '.join(sentence).capitalize() + '.'

join():将单词列表组合成一个字符串,并用 空格 连接它们。
capitalize():确保句子的首字母大写。
+ '.':在句子末尾加上句号,让其更符合语法规范。

生成的结果是这样:

generate_sentence(10)

Spodiosite caftan thyraden zoogeologist hobnailed pericardicentesis laniiform abjunction aftercure evaporativity.

猜你喜欢

转载自blog.csdn.net/zhang_jiamin/article/details/145897453
今日推荐