2017-01-26 21 views
-1

複数のテキストファイルの単語のリストを検索し、単語を含むファイルの数を計算したい。複数のテキストファイルの単語のリストを検索

私のコードでは、時間が数時間かかることがあります。

 uniqword = File.ReadAllLines(@"H:\\backstage\my work\uniqword.txt").ToList(); 
     string[] allfile = Directory.GetFiles(@"H:\\backstage\my work\categories file text\categories", "*.txt"); 
     var no_doc_word = new Dictionary<string, int>(); 

      foreach (string ff1 in allfile)// read one file in files until finish 
      { 
      List<string> allLinesText = File.ReadAllLines(ff1).ToList(); 

      foreach (string word in uniqword) 
       { 
       if (allLinesText.Contains(word)) 
        if (no_doc_word.ContainsKey(word)) 
         no_doc_word[word]++; 
        else 
         no_doc_word.Add(word, 1); 

      } 
     } 
+1

ここに質問はありません。 ReadAllTextを使用して、行ごとに1回ループするのはなぜですか?現在、あなたは異なる言い方をした言葉に匹敵せず、犬は犬と似合うでしょう。 –

+2

いくつのファイルがありますか?どのくらいのファイルがありますか? –

+1

これで何をしたいですか?私たちはあなたのコードを書き直すだけではありません。あなたの質問は何ですか? –

答えて

0

実際のボトルネックが何であるかに応じて、このような単純な何かが(コメントで説明を)それを行うことができます。

var words = new HashSet<string>(File.ReadAllLines(@"H:\\backstage\my work\uniqword.txt"));   // list of words 
    var filewords = Directory.GetFiles(@"H:\\backstage\my work\categories file text\categories", "*.txt")  
     .Select(f => File.ReadAllText(f))                // read all text in each file 
     .SelectMany(s => words.Intersect(Regex.Split(s, @"\W|_")))          // intersect the set of words in each file with the master list of words, then flatten the list 
     .GroupBy(s => s).ToDictionary(w => w.Key, w => w.Count());          // build a dictionary of each word and how many files it's used in 
+0

を含む文書は、最初の行 – Programmer

+0

にこのコードを読んではいけない最初の行を読んではいけない(=ファイルを終了し、CATIDをスキップするرسلから読み取る) 私のファイルがある:= 1 _رسل _جامعة _catId 。 。 – Programmer

+1

最初の行は何ですか? – Blindy

1

あなただけの単語をチェックし、あなたが読んでそれらを数えることができます

:ファイル:あなたも、あなたが欲しい、このように何度も呼び出すことができる非同期(async)

async Task Contains(string file) 
{ 
    using (StreamReader reader = new StreamReader(File.OpenRead(file)) 
    { 
     string line = string.Empty; 
     while((line = reader.ReadLine()) != null) 
     { 
      string[] words = line.Split(new char[] { ' ', ',', '.' }); 
      foreach(string word in uniqword) 
      { 
       int howMany = words.Count(w => w.Equals(word); 
       if (no_doc_word.ContainsKey(word)) 
        no_doc_word[word] += howMany; 
       else 
        no_doc_word.Add(word, howMany); 
      } 
     } 
    } 
} 

そして、これ以降は、

EDIT:このメソッドを使用してから

利点は、ファイル(またはほとんどすべて)のすべてが同じ時間で処理されていることです。

関連する問題