【问题标题】:Stopwords removing from string从字符串中删除停用词
【发布时间】:2016-07-25 08:54:15
【问题描述】:

我正在尝试从字符串中删除停用词,但问题是如果它再次出现在字符串中,它正在从单个单词中删除字符。
例如原始字符串是: “这部电影不错。” 结果字符串是: “这部电影不错。”。工作正常。但是
如果字符串是:“这部电影不错。
那么结果字符串将是:“th movie good.
由于 在此字符串中重复,因此它在结果中被排除。
另一个字符串: “这款游戏太棒了。所以,我观看并玩了很多。
结果:“gme fntstic。所以,我想拼多多。
由于 a 在此字符串中重复,因此结果字符串显示所有排除 a 的单词。

我正在唱这个代码:

List<string> stopWordsList = new List<string>();
stopWordsList = stopWordsFilter();//funtion returning the list of stop words taking from file.
        string propertyValue = "this game is fantastic. So, I watched and played a lot.";
        foreach (string word1 in propertyValue.Split(' '))
        {

            foreach ( var word in stopWordsList)
            {
                if (word.Equals(word1) && word.Length == word1.Length)
                {
                    propertyValue = propertyValue.Replace(word, "");
                }
            }
        }
        Console.WriteLine(propertyValue);

【问题讨论】:

标签: c# string stop-words


【解决方案1】:

问题是您将停用词替换为String.EmptyString.Replace 不关心单词,只关心子字符串。

您可以使用这种方法:

string propertyValue = "this game is fantastic. So, I watched and played a lot.";
var words = propertyValue.Split();
var newWords = words.Except(stopWordsFilter);
propertyValue = string.Join(" ", newWords);

如果你想忽略大小写,也可以省略"Is"

var newWords = words.Except(stopWordsFilter, StringComparer.InvariantCultureIgnoreCase);

【讨论】:

  • 非常感谢您的帮助。
  • 最好也使用其他分隔符。 var words = propertyValue.Split(new char[]{' ', ',', ';', '.' })
【解决方案2】:

我在这里提出一个使用 linq 的解决方案:

    string result = propertyValue.Split(' ')
        .Where(s => !stopWordsList.Contains(s))
        .Aggregate((current, next) => current + " " + next);
    Console.WriteLine(result);

【讨论】:

    猜你喜欢
    • 2013-12-16
    • 2014-05-22
    • 1970-01-01
    • 2014-06-06
    • 2015-02-25
    • 1970-01-01
    • 2019-12-18
    • 2016-10-06
    相关资源
    最近更新 更多