Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用多个不同的选项替换字符串_C#_String - Fatal编程技术网

C# 用多个不同的选项替换字符串

C# 用多个不同的选项替换字符串,c#,string,C#,String,嗨,这里有很多很棒的人 我现在的处境是我完全陷入困境。我想做的是从文本中取出一个单词,并用同义词替换它。我考虑了一会儿,并想出了如何做,如果我只有一个可能的同义词,这段代码 string pathToDesk = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string text = System.IO.File.ReadAllText(pathToDesk + "/Text.txt

嗨,这里有很多很棒的人

我现在的处境是我完全陷入困境。我想做的是从文本中取出一个单词,并用同义词替换它。我考虑了一会儿,并想出了如何做,如果我只有一个可能的同义词,这段代码

        string pathToDesk = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

        string text = System.IO.File.ReadAllText(pathToDesk + "/Text.txt");
        string replacementsText = System.IO.File.ReadAllText(pathToDesk + "/Replacements.txt");
        string wordsToReplace = System.IO.File.ReadAllText(pathToDesk + "/WordsToReplace.txt");

        string[] words = text.Split(' ');
        string[] reWords = wordsToReplace.Split(' ');
        string[] replacements = replacementsText.Split(' ');

        for(int i = 0; i < words.Length; i++) {//for each word 
            for(int j = 0; j < replacements.Length; j++) {//compare with the possible synonyms
                if (words[i].Equals(reWords[j], StringComparison.InvariantCultureIgnoreCase)) {
                    words[i] = replacements[j];
                }
            }
        }

        string newText = "";

        for(int i = 0; i < words.Length; i++) {
            newText += words[i] + " ";
        }

        txfInput.Text = newText;
string path todesk=Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string text=System.IO.File.ReadAllText(pathToDesk+“/text.txt”);
字符串replacementsText=System.IO.File.ReadAllText(pathToDesk+“/Replacements.txt”);
字符串wordsToReplace=System.IO.File.ReadAllText(pathToDesk+“/wordsToReplace.txt”);
string[]words=text.Split(“”);
string[]reWords=wordsToReplace.Split(“”);
字符串[]replacements=replacementsText.Split(“”);
对于(int i=0;i
但是我们要说的是,我们要得到“嗨”这个词。然后我想用{“你好”、“哟”、“你好”}来代替它;(例如)

那么我的代码将不会有任何用处,因为它们在数组中的位置不同


我真的很想知道有什么聪明的解决办法

您需要以不同的方式存储同义词

在您的文件中,您需要以下内容

hello yo hola hi
awesome fantastic great
然后对每一行拆分单词,将它们放入一个数组中

现在用它来寻找替换词

这不会得到超级优化,但您也可以轻松地将每个单词索引为一组同义词

差不多

public class SynonymReplacer
    {
        private Dictionary<string, List<string>> _synonyms;

        public void Load(string s)
        {
            _synonyms = new Dictionary<string, List<string>>();
            var lines = s.Split(new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
            foreach (var line in lines)
            {
                var words = line.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList();
                words.ForEach(word => _synonyms.Add(word, words));
            }
        }

        public string Replace(string word)
        {
            if (_synonyms.ContainsKey(word))
            {
                return _synonyms[word].OrderBy(a => Guid.NewGuid())
                                      .FirstOrDefault(w => w != word) ?? word;
            }
            return word;
        }
    }
你会得到:-

hello
ok
fantastic
hello you look fantastic

你的第一个任务是建立一个单词和同义词的列表。一本字典将是这方面的完美选择。包含此列表的文本文件可能如下所示:

word1|synonym11,synonym12,synonym13
word2|synonym21,synonym22,synonym23
word3|synonym31,synonym32,synonym33
public Dictionary<string, string[]> GetSynonymSet(string synonymSetTextFileFullPath)
{
    var dict = new Dictionary<string, string[]>();
    string line;

    // Read the file and display it line by line.
    using (var file = new StreamReader(synonymSetTextFileFullPath))
    {
        while((line = file.ReadLine()) != null)
        {
            var split = line.Split('|');
            if (!dict.ContainsKey(split[0]))
            {
                dict.Add(split[0], split[1].Split(','));
            }
        }
    }
    return dict;
}
然后您可以这样构造字典:

word1|synonym11,synonym12,synonym13
word2|synonym21,synonym22,synonym23
word3|synonym31,synonym32,synonym33
public Dictionary<string, string[]> GetSynonymSet(string synonymSetTextFileFullPath)
{
    var dict = new Dictionary<string, string[]>();
    string line;

    // Read the file and display it line by line.
    using (var file = new StreamReader(synonymSetTextFileFullPath))
    {
        while((line = file.ReadLine()) != null)
        {
            var split = line.Split('|');
            if (!dict.ContainsKey(split[0]))
            {
                dict.Add(split[0], split[1].Split(','));
            }
        }
    }
    return dict;
}
public Dictionary GetSynonymSet(字符串synonymSetTextFileFullPath)
{
var dict=新字典();
弦线;
//读取文件并逐行显示。
使用(var file=newstreamreader(同义词settextfilefullpath))
{
而((line=file.ReadLine())!=null)
{
var split=line.split(“|”);
如果(!dict.ContainsKey(拆分[0]))
{
dict.Add(拆分[0],拆分[1]。拆分(',');
}
}
}
返回命令;
}
最终的代码如下所示

public string ReplaceWordsInText(Dictionary<string, string[]> synonymSet, string text)
{
    var newText = new StringBuilder();
    string[] words = text.Split(' ');
    for (int i = 0; i < words.Length; i++) //for each word 
    {
        string[] synonyms;
        if (synonymSet.TryGetValue(words[i], out synonyms)
        {
            // The exact synonym you wish to use is up to you.
            // I will just use the first one
            words[i] = synonyms[0];
        }

        newText.AppendFormat("{0} ", words[i]);
    }

    return newText.ToString();
}
公共字符串替换词文本(字典同义词集,字符串文本)
{
var newText=新的StringBuilder();
string[]words=text.Split(“”);
for(int i=0;i
使用
字典
,使用单词作为键,使用同义词列表作为值。如果您的问题是保存/加载此数据,那么您可以使用XML序列化程序,这样您甚至可以手动创建文件。这部分起作用,任何同义词都需要有c#language.J所不熟悉的同义词的其余部分的键ust是几天前从java开始的。你有一个如何使用这些列表的工作示例吗?非常感谢。我可以问一下计数器++的用途吗?我似乎找不到它在程序中使用的位置或变量的位置。@AlbinWärme我已经编辑了答案。谢谢你指出这一点。