从字符串中删除的停用词

时间:2016-07-25 08:54:15

标签: c# string stop-words

我正在尝试从字符串中删除停用词,但问题是如果字符串中再次出现,则从单个字中删除字符。
例如原始字符串是: “这部电影很好。” 结果字符串是: “ 这部电影很好。 ”。工作正常。但是
如果字符串是:“这部电影很好。
然后结果字符串将是:“ 电影好。
由于 在此字符串中重复,因此在结果中免除。
另一个字符串:  “ 这个游戏太棒了。所以,我观看并玩了很多。 ” 结果:“ gme fntstic。所以,wtched plyed lot。
由于 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);

2 个答案:

答案 0 :(得分:4)

问题是你用String.Empty替换了停用词。 String.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);

答案 1 :(得分:1)

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

def in_or_add(s, x):
    return not(x in s or s.add(x))
相关问题