在C#中获取字符串组合

时间:2017-12-07 00:51:13

标签: c# string

Data

当我运行我的代码时,它会要求输入字符串并获取每个单词标记(漂亮和女王)的概率相似的单词列表。

我想要做的是混合输出,以便我可以获得wonderful queenwounderful princesslovely queenlovely empress等的列表。 ..

我目前的主要代码如下:

    while (true)
    {
        Console.Write("Input 1 > ");

        String word1 = Console.ReadLine();
        String[] splitted = word1.Split(' ');

        for(int i = 0; i < splitted.Length; i++)
        {
            foreach (var item in model.NearestWords(splitted[i], 10))
                Console.WriteLine("{0:0.000} {1}", item.Value, item.Key);
        }

        Console.WriteLine();
    }

获得similar strings of beautiful + similar strings of queen的所有可能性的好方法是什么?

1 个答案:

答案 0 :(得分:2)

实际上,我不知道你的框架的结构,但我可以指出你的解决方案,以获得形容词和名词的所有可能的组合:

List<String> adjectives = new List<String> { "Beautiful", "Wonderful", "Lovely" };
List<String> nouns = new List<String> { "Queen", "Princess", "Empress" };       

List<String> combinations = adjectives.SelectMany(a => nouns.Select(n => String.Concat(a, " ", n))).ToList();

for (Int32 i = 0; i < combinations.Count; ++i)
    Console.WriteLine(combinations[i]);

输出:

Beautiful Queen
Beautiful Princess
Beautiful Empress
Wonderful Queen
Wonderful Princess
Wonderful Empress
Lovely Queen
Lovely Princess
Lovely Empress

为了与平均概率一起获得组合:

public sealed class Word
{
    public Single Probability { get; private set; }
    public String Text { get; private set; }

    public Word(Single probability, String text)
    {
        Probability = probability;
        Text = text;
    }
}

List<Word> adjectives = new List<Word>
{
    new Word(1.000f, "Beautiful"),
    new Word(0.748f, "Wonderful"),
    new Word(0.732f, "Lovely")
};

List<Word> nouns = new List<Word>
{
    new Word(1.000f, "Queen"),
    new Word(0.767f, "Princess"),
    new Word(0.702f, "Empress")
};      

List<Word> words = adjectives
    .SelectMany(
        a => 
        nouns.Select(
            n => 
            new Word(((a.Probability + n.Probability) / 2.0f), String.Concat(a.Text, " ", n.Text))
        )
    )
    .ToList();

for (Int32 i = 0; i < words.Count; ++i)
{
    Word word = words[i];

    Console.WriteLine(word.Probability.ToString("N4") + " - " + word.Text);
}

输出:

1,0000 - Beautiful Queen
0,8835 - Beautiful Princess
0,8510 - Beautiful Empress
0,8740 - Wonderful Queen
0,7575 - Wonderful Princess
0,7250 - Wonderful Empress
0,8660 - Lovely Queen
0,7495 - Lovely Princess
0,7170 - Lovely Empress