3

いくつかのテキストファイルを含むディレクトリがあります。各ファイルの各単語の頻度をカウントするにはどうすればよいですか?単語とは、文字、数字、および下線文字を含むことができる文字のセットを意味します。

4

5 に答える 5

10

ファイル内のすべての単語の頻度をカウントする必要があるソリューションは次のとおりです。

    private void countWordsInFile(string file, Dictionary<string, int> words)
    {
        var content = File.ReadAllText(file);

        var wordPattern = new Regex(@"\w+");

        foreach (Match match in wordPattern.Matches(content))
        {
            int currentCount=0;
            words.TryGetValue(match.Value, out currentCount);

            currentCount++;
            words[match.Value] = currentCount;
        }
    }

このコードは次のように呼び出すことができます。

        var words = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);

        countWordsInFile("file1.txt", words);

この後、単語にはファイル内のすべての単語がその頻度とともに含まれます(たとえばwords["test"]、「テスト」がファイルコンテンツに含まれる回数を返します。複数のファイルからの結果を累積する必要がある場合は、すべてのファイルに対してメソッドを呼び出すだけです。同じ辞書を使用します。ファイルごとに個別の結果が必要な場合は、毎回新しい辞書を作成し、@DarkGrayが提案するような構造を使用します。

于 2012-03-31T11:43:34.350 に答える
3

imoがより単純なLinq風の代替手段があります。ここで重要なのは、組み込みのフレームワークFile.ReadLines(怠惰に読まれ、かっこいい)を使用することstring.Splitです。

private Dictionary<string, int> GetWordFrequency(string file)
{
    return File.ReadLines(file)
               .SelectMany(x => x.Split())
               .Where(x => x != string.Empty)
               .GroupBy(x => x)
               .ToDictionary(x => x.Key, x => x.Count());
}

多くのファイルから頻度を取得するには、に基づいてオーバーロードを設定できますparams

private Dictionary<string, int> GetWordFrequency(params string[] files)
{
    return files.SelectMany(x => File.ReadLines(x))
                .SelectMany(x => x.Split())
                .Where(x => x != string.Empty)
                .GroupBy(x => x)
                .ToDictionary(x => x.Key, x => x.Count());
}
于 2013-12-09T16:15:51.527 に答える
0

単語数:

int WordCount(string text)
{
  var regex = new System.Text.RegularExpressions.Regex(@"\w+");

  var matches = regex.Matches(text);
  return matches.Count;     
}

ファイルからテキストを読み取る:

string text = File.ReadAllText(filename);

単語カウント構造:

class FileWordInfo
{
  public Dictionary<string, int> WordCounts = new Dictionary<string, int>();
}

List<FileWordInfo> fileInfos = new List<FileWordInfo>();
于 2012-03-29T20:52:21.823 に答える
0

@aKzenTの答えは良いですが、問題があります!彼のコードは、その単語が辞書にすでに存在するかどうかをチェックすることはありません。だから私は次のようにコードを変更しました:

private void countWordsInFile(string file, Dictionary<string, int> words)
{
    var content = File.ReadAllText(file);

    var wordPattern = new Regex(@"\w+");

    foreach (Match match in wordPattern.Matches(content))
    {
        if (!words.ContainsKey(match.Value))
            words.Add(match.Value, 1);
        else
            words[match.Value]++;
    }
}
于 2013-12-09T14:57:22.647 に答える
0
string input= File.ReadAllText(filename);
var arr = input.Split(' ');
// finding frequencies of words in a string
IDictionary<string, int> dict = new Dictionary<string, int>();
foreach (var item in arr)
{
    var count = 0;
    if (dict.TryGetValue(item, out count))
        dict[item] = ++a;
    else
        dict.Add(item, 1);
}
于 2019-05-27T20:43:53.993 に答える