gpt4 book ai didi

c# - Spintax C# ...我该如何处理?

转载 作者:太空狗 更新时间:2023-10-30 00:20:59 25 4
gpt4 key购买 nike

Spintax 允许您旋转各种单词和句子,例如:

{Hello|Hi} {World|People}! {C{#|++|}|Java} is an {awesome|amazing} language.

大括号之间的文本将被随机选择以组成不同的句子。

我自己可能会想出一个解决方案,但我遇到的问题是嵌套。有时嵌套可以很深。处理嵌套的可能解决方案是什么?

我无法收集所需的逻辑。

最佳答案

不用担心嵌套,只需按如下方式迭代即可:

  1. 找到字符串中第一个包含 {...} 且内部没有其他大括号的序列。对于您的情况,这是 {Hello|Hi}。如果不再有该模式,请转到步骤 3。

  2. 从那里抓取所有可能性并随机选择一个,用它的值替换大括号部分。然后回到第一步。

  3. 这是您修改后的字符串。

假设您有一个总是返回零的随机数生成器略有故障。您的字符串修改历史将是:

a/ {Hello|Hi} {World|People}! {C{#|++|}|Java} is an {awesome|amazing} language.b/ Hello {World|People}! {C{#|++|}|Java} is an {awesome|amazing} language.c/ Hello World! {C{#|++|}|Java} is an {awesome|amazing} language.d/ Hello World! {C#|Java} is an {awesome|amazing} language.e/ Hello World! C# is an {awesome|amazing} language.f/ Hello World! C# is an awesome language.

Note particularly the transition from (c) to (d). Because we're looking for the first brace section that doesn't have braces inside it, we do the {#|++|} before the {C{#|++|}|Java}.

All you need to add now is the possibility that you may have {, } or | within your actual text - these will need to be escaped somehow to protect them from your modification engine.


Here's a little C# program which shows this in action. It's probably not that impressively written, given my relative inexperience with the language, but it illustrates the process.

using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
class Program
{
static string spintax(Random rnd, string str) {
// Loop over string until all patterns exhausted.
string pattern = "{[^{}]*}";
Match m = Regex.Match(str, pattern);
while (m.Success) {
// Get random choice and replace pattern match.
string seg = str.Substring(m.Index + 1, m.Length - 2);
string[] choices = seg.Split('|');
str = str.Substring(0, m.Index) + choices[rnd.Next(choices.Length)] + str.Substring(m.Index + m.Length);
m = Regex.Match(str, pattern);
}

// Return the modified string.
return str;
}

static void Main(string[] args) {
Random rnd = new Random();
string str = "{Hello|Hi} {World|People}! {C{#|++|}|Java} is an {awesome|amazing} language.";
Console.WriteLine(spintax(rnd, str));
Console.ReadLine();
}
}
}

在一个示例运行中,输出是

Hello World! C# is an awesome language.

关于c# - Spintax C# ...我该如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8004465/

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