【问题标题】:Replacing set of words with another [duplicate]用另一个替换一组单词[重复]
【发布时间】:2013-10-05 21:03:11
【问题描述】:

我知道如何使用以下代码将段落或文本文件中的特定单词替换为另一个单词:

String output = input.Replace("oldvalue","newvalue");

但我对替换一组单词感到困惑,替换 .我有将近 1000 个单词要替换。例如:

" aback " => " ashamed ",
" abacus " => " abacus ",
" abaft " => " aback ",
" abandon " => " carelessness ",
" abandoned " => " alone ",

因此,如果段落包含单词aback,我想用ashamed 替换它,就像每个单词一样。我们怎么能做到这一点?谁能给我一个想法?

【问题讨论】:

  • 如果单词数量有限,请在替换周围放置一个 for 循环,每个单词执行一次。如果单词很多,则将字符串解析为单词/部分,并为每个部分查找是否有替换。使用(替换的)解析部分构建新字符串。

标签: c# replace


【解决方案1】:

你可以这样写一个扩展方法

public static string ReplaceSetOfStrings(this string input, Dictionary<string, string> pairsToReplace)
{
    foreach (var wordToReplace in pairsToReplace)
    {
        input = input.Replace(wordToReplace.Key, wordToReplace.Value);
    }
    return input;
}

在上述方法中,Dictionary key 中会包含需要替换为 value 中要替换的单词的单词。

那你就可以这样称呼了

Dictionary<string,string> pairsToBeReplaced = new Dictionary<string,string>();
pairsToBeReplaced.Add(" aback "," ashamed ");
input.ReplaceSetOfStrings(pairsToBeReplaced);

【讨论】:

  • 哦,是的,现在这是一个优雅的解决方案。
  • 如果你有大量的词要替换,你可能更喜欢使用StringBuilder,见@RJK的回答
  • @没有一个好的答案!谢谢!
  • @NoOne 感谢它的工作:)
【解决方案2】:

由于您尝试替换实际单词,因此仅找到完整的单词(而不是部分单词)可能很重要,即使它们位于句子的开头(即大写)或句子的结尾(例如在他们之后有一段时间)。这需要一个正则表达式,因为您可以告诉它只查找带有 \b 的整个单词。

// This version will replace whole words (you don't need spaces around each one)
string ReplaceWords(string input, Dictionary<string, string> replacements)
{
    return Regex.Replace(
               input,
               @"\b(" 
                   + String.Join("|", replacements.Keys.Select(k => Regex.Escape(k)))
                   + @")\b", // pattern
               m => replacements[m.Value] // replacement
               );
}

// This version will replace capitalized words if the key is all lowercase
string ReplaceWords(string input, Dictionary<string, string> replacements)
{
    return Regex.Replace(
               input,
               @"\b(" 
                   + String.Join("|", replacements.Keys.Select(k => Regex.Escape(k)))
                   + @")\b", // pattern
               m => replacements[m.Value], // replacement
               RegexOptions.IgnoreCase);
}

private static string ReplaceWord(string word, Dictionary<string, string> replacements)
{
    string replacement;
    // see if word is in the dictionary as-is
    if (replacements.TryGetValue(word, out replacement))
        return replacement;
    // see if the all-lowercase version is in the dictionary
    if (replacements.TryGetValue(word.ToLower(), out replacement))
    {
        // if the word is all uppercase, make the replacement all uppercase
        if (word.ToUpper() == word)
            return replacement.ToUpper();
        // if the first letter is uppercase, make the replacement's first letter so
        if (char.IsUpper(word[0]))
            return char.ToUpper(replacement[0]) + replacement.Substring(1);
        // otherwise just return the replacement as-is
        return replacement;
    }
    // no replacement found, so don't replace
    return word;
}

如果字典中的键在调用之间没有变化,您可以编译 Regex 作为可能的优化。

【讨论】:

  • 感谢您的回答和它的工作酷。对不起,我已经编辑了你的答案以避免一些错误:)
  • @kavithai_kannan:感谢您修复我的代码。
【解决方案3】:

你可以像下面这样替换:Stolen from Here

StringBuilder sb = new StringBuilder("11223344");

    string myString =
        sb
          .Replace("1", string.Empty)
          .Replace("2", string.Empty)
          .Replace("3", string.Empty)
          .ToString();

或者你也可以这样做:Stolen from Here

// Define name/value pairs to be replaced.
var replacements = new Dictionary<string,string>();
replacements.Add("<Name>", client.FullName);
replacements.Add("<EventDate>", event.EventDate.ToString());

// Replace
string s = "Dear <Name>, your booking is confirmed for the <EventDate>";
foreach (var replacement in replacements)
{
   s = s.Replace(replacement.Key, replacement.Value);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 2014-08-12
    相关资源
    最近更新 更多