gpt4 book ai didi

Python - 分词、替换单词

转载 作者:行者123 更新时间:2023-11-28 21:24:01 26 4
gpt4 key购买 nike

我正在尝试创建类似句子的东西,其中包含随机单词。具体来说,我会有类似的东西:

"The weather today is [weather_state]."

并且能够做一些事情,比如找到 [brackets] 中的所有标记,而不是将它们交换为字典或列表中的随机对应物,给我留下:

"The weather today is warm."
"The weather today is bad."

"The weather today is mildly suiting for my old bones."

请记住,[bracket] 标记的位置不会始终处于同一位置,并且我的字符串中会有多个括号标记,例如:

"[person] is feeling really [how] today, so he's not going [where]."

我真的不知道从哪里开始,或者这是否是使用标记化或标记模块的最佳解决方案。非常感谢任何能给我指明正确方向的提示!

编辑:澄清一下,我真的不需要使用方括号,任何非标准字符都可以。

最佳答案

您正在寻找带有回调函数的 re.sub:

words = {
'person': ['you', 'me'],
'how': ['fine', 'stupid'],
'where': ['away', 'out']
}

import re, random

def random_str(m):
return random.choice(words[m.group(1)])


text = "[person] is feeling really [how] today, so he's not going [where]."
print re.sub(r'\[(.+?)\]', random_str, text)

#me is feeling really stupid today, so he's not going away.

请注意,与format 方法不同,这允许对占位符进行更复杂的处理,例如

[person:upper] got $[amount if amount else 0] etc

基本上,您可以在此基础上构建自己的“模板引擎”。

关于Python - 分词、替换单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16583740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com