Пример #1
0
        /// <summary>
        /// 加载内存词库
        /// </summary>
        public static void Load(HashSet <string> words)
        {
            List <string> wordList = new List <string>();

            Array.Clear(MEMORYLEXICON, 0, MEMORYLEXICON.Length);
            foreach (string word in words)
            {
                string key = ToDBC(word);
                wordList.Add(key);
            }
            for (int i = wordList.Count - 1; i > 0; i--)
            {
                if (wordList[i].ToString() == wordList[i - 1].ToString())
                {
                    wordList.RemoveAt(i);
                }
            }
            foreach (var word in wordList)
            {
                if (word.Length > 0)
                {
                    WordGroup group = MEMORYLEXICON[(int)word[0]];
                    if (group == null)
                    {
                        group = new WordGroup();
                        MEMORYLEXICON[(int)word[0]] = group;
                    }
                    group.Add(word.Substring(1));
                }
            }
            CLog.Info("加载脏词库成功");
        }
Пример #2
0
 public void FilterCheck()
 {
     cursor = 0;
     if (sourctText != string.Empty)
     {
         char[] tempString = sourctText.ToCharArray();;
         for (int i = 0; i < SourctText.Length; i++)
         {
             //查询以该字为首字符的词组
             WordGroup group = MEMORYLEXICON[(int)ToDBC(SourctText)[i]];
             if (group != null)
             {
                 for (int z = 0; z < group.Count(); z++)
                 {
                     string word = group.GetWord(z);
                     if (word.Length == 0 || Check(word))
                     {
                         IsSensitive = true;
                         string blackword = string.Empty;
                         for (int pos = 0; pos < wordlenght + 1; pos++)
                         {
                             blackword += tempString[pos + cursor].ToString();
                         }
                         illegalWords.Add(blackword);
                         cursor = cursor + wordlenght;
                         i      = i + wordlenght;
                     }
                 }
             }
             cursor++;
         }
     }
 }
Пример #3
0
        public ActionResult DeleteConfirmed(int id)
        {
            WordGroup       wordGroup         = db.WordGroup.Find(id);
            var             wordGroupSynonyms = db.WordGroupSynonym.Where(w => w.WordGroupId == wordGroup.Id);
            List <Synonyms> synonyms          = new List <Synonyms>();


            foreach (var wordGroupSynonym in wordGroupSynonyms)
            {
                synonyms.AddRange(db.Synonyms.Where(s => s.SynonymId == wordGroupSynonym.SynonymId));
            }

            foreach (var item in synonyms)
            {
                db.Word.Remove(db.Word.Find(item.WordId));
                var dbSynonyms = db.Synonyms.Where(i => i.SynonymId == item.SynonymId);
                if (dbSynonyms != null)
                {
                    db.Synonyms.RemoveRange(dbSynonyms);
                }
            }
            db.WordGroupSynonym.RemoveRange(wordGroupSynonyms);
            db.WordGroup.Remove(wordGroup);
            db.SaveChanges();

            return(RedirectToAction("Index"));
        }
Пример #4
0
        public IHttpActionResult PutWordGroup(string id, WordGroup wordGroup)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != wordGroup.Id)
            {
                return(BadRequest());
            }

            db.Entry(wordGroup).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!WordGroupExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Пример #5
0
        public IHttpActionResult PostWordGroup(WordGroup wordGroup)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.WordGroups.Add(wordGroup);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateException)
            {
                if (WordGroupExists(wordGroup.Id))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtRoute("DefaultApi", new { id = wordGroup.Id }, wordGroup));
        }
Пример #6
0
        public ActionResult DeleteConfirmed(int id)
        {
            WordGroup wordGroup = db.WordGroups.Find(id);

            db.WordGroups.Remove(wordGroup);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Пример #7
0
 public ActionResult Edit([Bind(Include = "Id,Description,UserId")] WordGroup wordGroup)
 {
     if (ModelState.IsValid)
     {
         db.Entry(wordGroup).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(wordGroup));
 }
Пример #8
0
        public IHttpActionResult GetWordGroup(string id)
        {
            WordGroup wordGroup = db.WordGroups.Find(id);

            if (wordGroup == null)
            {
                return(NotFound());
            }

            return(Ok(wordGroup));
        }
Пример #9
0
        public ActionResult Create([Bind(Include = "Id,Name,LevelId")] WordGroup wordGroup)
        {
            if (ModelState.IsValid)
            {
                db.WordGroups.Add(wordGroup);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(wordGroup));
        }
Пример #10
0
        public IHttpActionResult DeleteWordGroup(string id)
        {
            WordGroup wordGroup = db.WordGroups.Find(id);

            if (wordGroup == null)
            {
                return(NotFound());
            }

            db.WordGroups.Remove(wordGroup);
            db.SaveChanges();

            return(Ok(wordGroup));
        }
Пример #11
0
        private int GetWordGroup(int userId, string wordGroupName)
        {
            WordGroup wordGroup = db.WordGroup.Where(n => n.Description == wordGroupName && n.UserId == userId).FirstOrDefault();

            if (wordGroup == null)
            {
                wordGroup = new WordGroup {
                    Description = wordGroupName, UserId = userId
                };
                db.WordGroup.Add(wordGroup);
                db.SaveChanges();
            }
            return(wordGroup.Id);
        }
Пример #12
0
        // GET: WordGroups/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            WordGroup wordGroup = db.WordGroup.Find(id);

            if (wordGroup == null)
            {
                return(HttpNotFound());
            }
            return(View(wordGroup));
        }
Пример #13
0
 /// <summary>
 /// 查找并替换
 /// </summary>
 /// <param name="replaceChar"></param>
 public static string Filter(string text, char replaceChar = '*')
 {
     cursor     = 0;
     wordlenght = 0;
     IllegalWords.Clear();
     SourctText = text;
     if (SourctText != string.Empty)
     {
         char[] tempString = SourctText.ToCharArray();
         for (int i = 0; i < SourctText.Length; i++)
         {
             //查询以该字为首字符的词组
             WordGroup group = MEMORYLEXICON[(int)ToDBC(SourctText)[i]];
             if (group != null)
             {
                 for (int z = 0; z < group.Count(); z++)
                 {
                     string word = group.GetWord(z);
                     if (word.Length == 0 || Check(word))
                     {
                         string blackword = string.Empty;
                         for (int pos = 0; pos < wordlenght + 1; pos++)
                         {
                             if ((pos + cursor) >= tempString.Length)
                             {
                                 continue;
                             }
                             blackword += tempString[pos + cursor].ToString();
                             tempString[pos + cursor] = replaceChar;
                         }
                         IllegalWords.Add(blackword);
                         cursor = cursor + wordlenght;
                         i      = i + wordlenght;
                     }
                 }
             }
             cursor++;
         }
         return(new string(tempString));
     }
     else
     {
         return(string.Empty);
     }
 }
        public static string ToGradeStr(this WordGroup group)
        {
            switch (group)
            {
            case WordGroup.A_DefinitelyKnown: return("A");

            case WordGroup.B_WellKnown: return("B");

            case WordGroup.C_KindaKnown: return("C");

            case WordGroup.D_NeedToMemorize: return("D");

            case WordGroup.E_TotallyUnknown: return("E");

            default:
                return(group.ToString());
            }
        }
        public static string ToFullStr(this WordGroup group)
        {
            switch (group)
            {
            case WordGroup.A_DefinitelyKnown: return($"({group.ToGradeStr()}) {PrgResources.WGDefinitelyKnown}");

            case WordGroup.B_WellKnown:       return($"({group.ToGradeStr()}) {PrgResources.WGWellKnown}");

            case WordGroup.C_KindaKnown:      return($"({group.ToGradeStr()}) {PrgResources.WGKindOfKnown}");

            case WordGroup.D_NeedToMemorize:  return($"({group.ToGradeStr()}) {PrgResources.WGNeedToMemorize}");

            case WordGroup.E_TotallyUnknown:  return($"({group.ToGradeStr()}) {PrgResources.WGTotallyUnknown}");

            default:
                return(group.ToString());
            }
        }
Пример #16
0
        /// <summary>
        /// 查找并替换
        /// </summary>
        /// <param name="replaceChar"></param>
        public string Filter(char replaceChar)
        {
            if (sourctText != string.Empty)
            {
                char[] tempString = sourctText.ToCharArray();

                var dbcarray = ToDBC(SourctText);
                int index;
                for (int i = 0; i < SourctText.Length; i++)
                {
                    if (dbcarray.Length <= i)
                    {
                        continue;
                    }
                    index = (int)dbcarray[i];
                    WordGroup group = MEMORYLEXICON[index];
                    if (group != null)
                    {
                        for (int z = 0; z < group.Count; z++)
                        {
                            string word = group.GetWord(z);
                            if (word.Length == 0 || Check(word))
                            {
                                string blackword = string.Empty;
                                for (int pos = 0; pos < wordlenght + 1; pos++)
                                {
                                    blackword += tempString[pos + cursor].ToString();
                                    tempString[pos + cursor] = replaceChar;
                                }
                                illegalWords.Add(blackword);
                                cursor = cursor + wordlenght;
                                i      = i + wordlenght;
                            }
                        }
                    }
                    cursor++;
                }
                return(new string(tempString));
            }
            else
            {
                return(string.Empty);
            }
        }
Пример #17
0
 /// <summary>
 /// 加载内存词库
 /// </summary>
 private void LoadDictionary()
 {
     if (SensitiveTextFile != null)
     {
         List <string> wordList = new List <string>();
         Array.Clear(MEMORYLEXICON, 0, MEMORYLEXICON.Length);
         string[] words = SensitiveTextFile.text.Split(new char[] { '\r', '\n' });/*System.IO.File.ReadAllLines(DictionaryPath, System.Text.Encoding.UTF8);*/
         foreach (string word in words)
         {
             string key = this.ToDBC(word);
             if (key == null || key == string.Empty)
             {
                 continue;
             }
             wordList.Add(key);
             //Debug.Log("key = " + key);
             //wordList.Add(Microsoft.VisualBasic.Strings.StrConv(key, Microsoft.VisualBasic.VbStrConv.TraditionalChinese, 0));
         }
         Comparison <string> cmp = delegate(string key1, string key2)
         {
             return(key1.CompareTo(key2));
         };
         wordList.Sort(cmp);
         for (int i = wordList.Count - 1; i > 0; i--)
         {
             if (wordList[i].ToString() == wordList[i - 1].ToString())
             {
                 wordList.RemoveAt(i);
             }
         }
         foreach (var word in wordList)
         {
             //Debug.Log("word = " + word);
             WordGroup group = MEMORYLEXICON[(int)word[0]];
             if (group == null)
             {
                 group = new WordGroup();
                 MEMORYLEXICON[(int)word[0]] = group;
             }
             group.Add(word.Substring(1));
         }
     }
 }
Пример #18
0
 /// <summary>
 /// 加载内存词库
 /// </summary>
 private void LoadDictionary()
 {
     if (DictionaryPath != string.Empty)
     {
         //一个字词集合列表
         List <string> wordList = new List <string>();
         //清理内存缓存字词组
         Array.Clear(MEMORYLEXICON, 0, MEMORYLEXICON.Length);
         //加载词库文件,一行一个
         string[] words = GetDictionaryContext();
         foreach (string word in words)
         {
             string key = this.ToDBC(word);
             wordList.Add(key);
             //将简体字转换为繁体字词
             //wordList.Add(Microsoft.VisualBasic.Strings.StrConv(key, Microsoft.VisualBasic.VbStrConv.TraditionalChinese, 0));
         }
         Comparison <string> cmp = delegate(string key1, string key2)
         {
             return(key2.CompareTo(key1));
         };
         //排序后去重
         wordList.Sort(cmp);
         for (int i = wordList.Count - 1; i > 0; i--)
         {
             if (wordList[i].ToString() == wordList[i - 1].ToString())
             {
                 wordList.RemoveAt(i);
             }
         }
         foreach (var word in wordList)
         {
             WordGroup group = MEMORYLEXICON[(int)word[0]];
             if (group == null)
             {
                 group = new WordGroup();
                 MEMORYLEXICON[(int)word[0]] = group;
             }
             group.Add(word.Substring(1));
         }
     }
 }
Пример #19
0
        public async Task <IActionResult> AddWordToGroup(int groupId, int wordId)
        {
            try
            {
                var wordFromDb = await _repo.GetOneWithCondition <Word>(w => w.Id == wordId);

                if (wordFromDb == null)
                {
                    return(NotFound());
                }
                var wordInGroup = await _repo.GetOneWithCondition <WordGroup>(w => w.WordId == wordId && w.GroupId == groupId);

                if (wordInGroup != null)
                {
                    _repo.Delete(wordInGroup);
                    if (await _repo.SaveAll())
                    {
                        return(Ok());
                    }
                    return(NoContent());
                }
                else
                {
                    var wordGroup = new WordGroup()
                    {
                        WordId  = wordId,
                        GroupId = groupId
                    };
                    _repo.Create(wordGroup);
                    if (await _repo.SaveAll())
                    {
                        return(Ok());
                    }
                    return(NoContent());
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }
Пример #20
0
        public ActionResult Create([Bind(Include = "Id,Description")] WordGroup wordGroup)
        {
            if (ModelState.IsValid)
            {
                int userId = 0;
                if (Session["UserId"] != null)
                {
                    userId = int.Parse(Session["UserId"].ToString());
                }
                else
                {
                    return(HttpNotFound("Error UserId for creator not found"));
                }

                wordGroup.UserId = userId;
                db.WordGroup.Add(wordGroup);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(wordGroup));
        }
Пример #21
0
        private void DoAddWord(string obj)
        {
            Console.WriteLine("enter DoAddWord");
            addWordDialog = new AddWordDialog();
            if (addWordDialog.ShowDialog() == false)
            {
                if (addWordDialog.NewWordEnglish != null && addWordDialog.NewWordGerman != null)
                {
                    string newWordE = addWordDialog.NewWordEnglish;
                    string newWordG = addWordDialog.NewWordGerman;
                    Console.WriteLine("New Word: " + newWordE + " : " + newWordG);

                    WordGroup newWG = new WordGroup();
                    newWG.Word_en  = newWordE;
                    newWG.Word_ge  = newWordG;
                    newWG.Category = selectedCategory;
                    words_db.WordGroups.Add(newWG);
                    words_db.SaveChanges();

                    Words = words_db.WordGroups.Where(x => x.Category.CategoryId == selectedCategory.CategoryId)
                            .Select(x => x).AsObservableCollection();
                }
            }
        }
Пример #22
0
        protected override void Seed(DB_lib.WordsContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.
            Console.WriteLine("Seeding...");
            try
            {
                Category environment = new Category {
                    CategoryName = "Environment"
                };
                Category cars = new Category {
                    CategoryName = "Cars"
                };
                Category food = new Category {
                    CategoryName = "Food"
                };
                Category colors = new Category {
                    CategoryName = "Colors"
                };

                WordGroup tree = new WordGroup {
                    Word_en = "tree", Word_ge = "Baum", Category = environment
                };
                WordGroup lake = new WordGroup {
                    Word_en = "lake", Word_ge = "See", Category = environment
                };
                WordGroup mountain = new WordGroup {
                    Word_en = "mountain", Word_ge = "Berg", Category = environment
                };
                WordGroup forest = new WordGroup {
                    Word_en = "forest", Word_ge = "Wald", Category = environment
                };
                WordGroup desert = new WordGroup {
                    Word_en = "desert", Word_ge = "Wüste", Category = environment
                };


                WordGroup apple = new WordGroup {
                    Word_en = "apple", Word_ge = "Apfel", Category = food
                };
                WordGroup banana = new WordGroup {
                    Word_en = "banana", Word_ge = "Banane", Category = food
                };
                WordGroup pork = new WordGroup {
                    Word_en = "pork", Word_ge = "Schweinefleisch", Category = food
                };
                WordGroup tomato = new WordGroup {
                    Word_en = "tomato", Word_ge = "Tomate", Category = food
                };
                WordGroup cucumber = new WordGroup {
                    Word_en = "cucumber", Word_ge = "Gurke", Category = food
                };

                WordGroup red = new WordGroup {
                    Word_en = "red", Word_ge = "rot", Category = colors
                };
                WordGroup green = new WordGroup {
                    Word_en = "green", Word_ge = "grün", Category = colors
                };
                WordGroup blue = new WordGroup {
                    Word_en = "blue", Word_ge = "blau", Category = colors
                };
                WordGroup black = new WordGroup {
                    Word_en = "black", Word_ge = "schwarz", Category = colors
                };

                WordGroup hatchback = new WordGroup {
                    Word_en = "hatchback", Word_ge = "kompaktwagen", Category = cars
                };
                WordGroup sedan = new WordGroup {
                    Word_en = "sedan", Word_ge = "limousine", Category = cars
                };
                WordGroup estate = new WordGroup {
                    Word_en = "estate", Word_ge = "kombi", Category = cars
                };


                context.Categories.AddOrUpdate(environment);
                context.Categories.AddOrUpdate(cars);
                context.Categories.AddOrUpdate(food);
                context.Categories.AddOrUpdate(colors);


                context.WordGroups.AddOrUpdate(tree);
                context.WordGroups.AddOrUpdate(lake);
                context.WordGroups.AddOrUpdate(mountain);
                context.WordGroups.AddOrUpdate(desert);
                context.WordGroups.AddOrUpdate(forest);

                context.WordGroups.AddOrUpdate(apple);
                context.WordGroups.AddOrUpdate(banana);
                context.WordGroups.AddOrUpdate(pork);
                context.WordGroups.AddOrUpdate(tomato);
                context.WordGroups.AddOrUpdate(cucumber);

                context.WordGroups.AddOrUpdate(red);
                context.WordGroups.AddOrUpdate(green);
                context.WordGroups.AddOrUpdate(blue);
                context.WordGroups.AddOrUpdate(black);

                context.WordGroups.AddOrUpdate(hatchback);
                context.WordGroups.AddOrUpdate(sedan);
                context.WordGroups.AddOrUpdate(estate);

                Console.WriteLine("Saving changes from migration");
                context.SaveChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error***************** " + e.Message);
            }
        }
Пример #23
0
        /// <summary>
        /// Обработчик нажатия на кнопку с буквой
        /// </summary>
        /// <param name="sender">Объект кнопки</param>
        /// <param name="e">Аргументы события</param>
        private void CharButton_Click(object sender, EventArgs e)
        {
            // если нет слова для игры - выходим и ничего не делаем
            if (currentWord == null)
            {
                return;
            }

            if (sender is Button button)
            {
                // скрываем кнопку
                button.Hide();

                // проверяем, есть ли выбранная буква в слове
                if (currentWord.Word.ToUpper().Contains(button.Text))
                {
                    // открываем буквы в слове
                    for (int i = currentWord.Word.ToUpper().IndexOf(button.Text); i > -1; i = currentWord.Word.ToUpper().IndexOf(button.Text, i + 1))
                    {
                        StringBuilder sb = new StringBuilder(WordLabel.Text);
                        sb[i]          = Char.Parse(button.Text);
                        WordLabel.Text = sb.ToString();
                    }
                }
                else
                {
                    errorCount++;

                    // в зависимости от номера текущей ошибки устанавливаем соответствующее изображение
                    switch (errorCount)
                    {
                    case 1:
                        GallowsImage.Image = Resources.Висельница2;
                        break;

                    case 2:
                        GallowsImage.Image = Resources.Висельница3;
                        break;

                    case 3:
                        GallowsImage.Image = Resources.Висельница4;
                        break;

                    case 4:
                        GallowsImage.Image = Resources.Висельница5;
                        break;

                    case 5:
                        GallowsImage.Image = Resources.Висельница6;
                        break;

                    case 6:
                        GallowsImage.Image = Resources.Висельница7;
                        break;
                    }

                    // если количество ошибок достигло 6, значит проиграли
                    if (errorCount == 6)
                    {
                        MessageBox.Show($"\nСлово: {currentWord.Word}\nОписание: {currentWord.Description}",
                                        "Вы проиграли!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        InitializeNewGame();
                    }
                }

                // если не осталось ни одного знака *, значит выиграли
                if (!WordLabel.Text.Contains("*"))
                {
                    MessageBox.Show($"\nСлово: {currentWord.Word}\nОписание: {currentWord.Description}",
                                    "Вы выиграли!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

            WordGroup.Focus();
        }
Пример #24
0
        /// <summary>
        /// 类初始化
        /// </summary>
        /// <param name="wordDict">敏感词集合(key-敏感词,value-替换字符)</param>
        private void Initialization(Dictionary<string, string> wordDict)
        {
            Array.Clear(_wordTable, 0, _wordTable.Length);

            List<WordEntity> wordList = new List<WordEntity>();
            WordFilterStatus status;

            foreach (var pair in wordDict)
            {
                StringBuilder wordBuilder = new StringBuilder();
                string tempWord = pair.Key;
                status = WordFilterStatus.Replace;

                string replacement = string.IsNullOrEmpty(pair.Value) ? "*" : pair.Value;
                if (replacement == "{Banned}") status = WordFilterStatus.Banned;

                if (pair.Key.StartsWith("\""))
                {
                    //转换成繁体再加载一个
                    WordEntity regexWord = new WordEntity()
                    {
                        Word = pair.Key.Trim('\"'),
                        Replacement = replacement,
                        WordFilterStatus = status
                    };

                    _regexWords.Add(regexWord);

                    continue;
                }

                tempWord = IgnoreCharacterProcess(pair.Key);

                for (int i = 0; i < tempWord.Length; i++)
                {
                    wordBuilder.Append((char)FastToLower(tempWord[i])); //统一转换成小写
                }

                //添加到列表
                WordEntity simpleWord = new WordEntity()
                {
                    Word = wordBuilder.ToString(),
                    Replacement = replacement,
                    WordFilterStatus = status
                };

                wordList.Add(simpleWord);
            }

            _regexWords = _regexWords.OrderByDescending(n => n.WordFilterStatus).ToList();

            //去除重复
            Comparison<WordEntity> cmp = delegate(WordEntity a, WordEntity b)
            {
                return a.Word.CompareTo(b.Word);
            };

            wordList.Sort(cmp);
            for (int idx = wordList.Count - 1; idx > 0; idx--)
            {
                if (wordList[idx].Word == wordList[idx - 1].Word)
                {
                    wordList.RemoveAt(idx);
                }
            }

            //添加到字典
            foreach (WordEntity entity in wordList)
            {
                WordGroup group = _wordTable[(int)entity.Word[0]];

                if (group == null)
                {
                    group = new WordGroup();
                    group.AppendWord(entity.Word.Substring(1), entity.WordFilterStatus, entity.Replacement);
                    _wordTable[(int)entity.Word[0]] = group;
                }
                else
                {
                    group.AppendWord(entity.Word.Substring(1), entity.WordFilterStatus, entity.Replacement);
                }
            }
        }