2017-08-23 13 views
2

リストや文字列は、次のとおりです。リストと文字列を比較し、C#を使用して文字列内の一致する単語を見つける方法は?

string Text; 
List<string> Names = new List<string>(); 

今、データベースからリストにデータをロード:

今すぐ文字列にデータをロードする
string connectionString = "Data Source=SANGEEN-PC;Initial Catalog=IS_Project;Integrated Security=True;Connection Timeout=0"; 

using (SqlConnection cnn = new SqlConnection(connectionString)) 
{ 
    try 
    { 
     SqlDataAdapter da = new SqlDataAdapter("select NamesValues from Names", cnn); 
     DataSet ds = new DataSet(); 
     da.Fill(ds, "Names"); 

     foreach (DataRow row in ds.Tables["Names"].Rows) 
     { 
      Names.Add(row["NamesValues"].ToString()); 
     } 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show("Can not open connection ! "); 
    } 
} 

Text = System.IO.File.ReadAllText(@"D:\Data-Sanitization-Project\Files\Test.txt"); 

は、今、私が比較したいです名前とテキストは次のようになります。

  1. 文字列(マッチした単語)にもあるすべてのリストアイテムを検索し、リストまたは配列に格納します。
  2. 見つかったすべての一致する単語を「名前」に置き換えます。
  3. 一致する単語を数えます。

例:

Names:     Text:         

Sangeen Khan   I am Sangeen Khan and i am friend  
Jhon     Jhon. Jhon is friend of Wasim.        
Wasim 
Alexander 
Afridi 

所望の動作:上記の3つの点については

Matched List/Array: Matches:   Updated Text:   

Sangeen Khan   4   I am "Name" and i am friend     
Jhon        "Name". "Name" is friend of "Names". 
Wasim 

、私は次のコードを書かれているが、それは働いていない:

var TextRead = File.ReadAllLines(text); 
HashSet<string> hashSet = new HashSet<string>(TextRead); 

foreach (string i in Names) 
{ 
    if (hashSet.Contains(i)) 
    { 
     MessageBox.Show("found"); 
    } 
} 

私は自分の問題を説明するために最善を尽くしているが、編集する必要があることを理解している場合は、私の質問を編集してください。前もって感謝します。

+0

以前にリストを持っていたときに、なぜハッシュセットを使用していますか? Names.Contains()を試しましたか? –

+0

@David Lindon The Textは文字列で、その文字列Textで単語を見つけようとしています。私は思っていません.Contains()は文字列で使用することができます –

+0

カウントのために、すべての部分文字列または一致する単語だけを数えたいですか?あなたの定義にある言葉は何ですか?それはスペースで区切られていますか、または区切り文字で区切られていますか? –

答えて

2
  1. 文字列(一致する単語)にも含まれるすべてのリストアイテムを検索し、リストまたは配列に格納します。
  2. 見つかったすべての一致する単語を「名前」に置き換えます。
  3. 一致する単語を数えます。

  1. List<string> matchedWords = Names.Where(Text.Contains).ToList();
  2. matchedWords.ForEach(w => Text = Text.Replace(w, "Names"));
  3. int numMatchedWords = matchedWords.Count;

numMatchedWordsはそうでも繰り返し、テキスト内のすべての一致をカウントしなければならないようです。そして、あなたは(Replace前)は、次のアプローチを使用することができます。

このエクステンションは、テキスト内のすべての単語の出現回数を見つける:

public static Dictionary<string, int> OccurencesInText(this IEnumerable<string> words, string text, StringComparison comparison = StringComparison.OrdinalIgnoreCase) 
{ 
    if (text == null) throw new ArgumentNullException(nameof(text)); 

    Dictionary<string, int> resultDict = new Dictionary<string, int>(); 
    foreach (string word in words.Distinct()) 
    { 
     int wordOccurrences = 0; 
     for(int i = 0; i < text.Length - word.Length; i++) 
     { 
      string substring = text.Substring(i, word.Length); 
      if (substring.Equals(word, comparison)) wordOccurrences++; 
     } 
     resultDict.Add(word, wordOccurrences); 
    } 
    return resultDict; 
} 

は使用方法:

int numMatchedWords = matchedWords.OccurencesInText(Text).Sum(kv => kv.Value); 
+0

私はこれがOPが望んでいるものと正確には思わない。彼の例を見ると、マッチ回数は4回( "Jhon"が繰り返されます)あなたのコードでは、マッチは3回になります。 – Pikoh

+0

Hmm。ちょうどチェックしています。あなたは別の問題があると思います。テキストを単語に分割した数を数えますが、いくつかの名前(Sangeen Khan)は実際には2つの単語です。だから私の答えで私は最初に名前を置き換えてカウント:) – Pikoh

+0

ああ、はい、しかし、OPは、4つの試合を期待している例では、私はそれがtypo(私はまた、JhonのOPの代わりに、ジョンを意味したと仮定して); – Pikoh

0

あなたのを実行することができますループ内の名前を検索し、Regexで名前を検索すると、 MatchCount> 0の場合、テキストを置き換えて グローバルMatchCountをカウントアップすることができます。

Match.Count == 0. 次に、この名前を2番目のリストに追加できます。その後、for Each Loopの後にリストから名前を削除できます。

 public static List<string> Names = new List<string>(); 
    public static string Text = "I am Sangeen Khan and i am friend Jhon. Jhon is friend of Wasim."; 
    static void Main(string[] args) 
    { 
     Names.Add("Sangeen Khan"); 
     Names.Add("Jhon"); 
     Names.Add("Wasim"); 
     Names.Add("Alexander"); 
     Names.Add("Afridi"); 

     var matchCount = 0; 
     var nameToRemove = new List<string>(); 
     foreach (var name in Names) 
     { 
      var regex = new Regex(name); 
      var match = regex.Matches(Text); 

      //Count of matches 
      matchCount += match.Count; 

      if (match.Count > 0) 
      { 
       Text = regex.Replace(Text, "\"Name\""); 
      } 
      else 
      { 
       nameToRemove.Add(name); 
      } 
     } 
     nameToRemove.ForEach(name=> Names.Remove(name)); 
     Console.WriteLine($"Names: {string.Join(" ", Names)}"); 
     Console.WriteLine($"Count: {matchCount}"); 
     Console.WriteLine($"ReplaceText: {Text}"); 
     Console.ReadLine(); 
    } 

出力

名:SangeenカーンJHON Wasim

数:4

のreplaceText:私は "名前" と私は友人の "名前" です。 "名前"は "名前"の友達です。

0
static void Main() 
    { 
     var count = 0; 

     string text = "I am Sangeen Khan and i am friend Jhon. Jhnon is friend of Wasim.  "; 
     List<string> Names = new List<string>() {"Sangeen Khan ", "Jhon","Wasim","Alexander","Afridi" }; 
     List<string> matchedList = new List<string>(); 

     foreach (var name in Names) 
     { 
      if(text.Contains(name)) 
      { 
       text = text.Replace(name, "\"Name\" "); 
       matchedList.Add(name); 
       count++; 
      } 
     } 

     foreach (var name in matchedList) 
     {     
      Console.WriteLine(name); 
     } 

     Console.WriteLine(count); 
     Console.WriteLine(text); 

     Console.ReadLine(); 
    } 
0

あなたのリストの名前を '名前'に置き換えたいので、まずそれを行い、テキスト中の「名前」をカウントします。次のようなものがあります。

string[] names = new string[] { "Sangeen Khan", "Jhon", "Wasim", "Alexander", "Afridi" }; 
string text = "I am Sangeen Khan and i am friend Jhon. Jhon is friend of Wasim."; 

foreach(string name in names) 
{ 
    text = text.Replace(name, "'Name'"); 
} 

int matches = Regex.Matches(Regex.Escape(text), "'Name'").Count; 
+0

データベースからロードする際にデータベースからデータを読み込んだ親愛なる友人 –

+0

@SangeenKhanコードをデバッグする必要がありますあなたがDBからロードするときにリストにあるものを見る... – Pikoh

関連する問題