C# C控制台。。。文本阅读、字数计算应用程序
好的,我有一个C控制台应用程序,它被支持读取一个.txt文件…并计算不同的单词..它可以工作..但是我用一个100MB的文件来读取文件中每个不同的单词,它会持续几天。。 我想要的是一种方法,读取文件一次,并计算所有不同的单词。 以下是迄今为止该应用程序的一些示例:C# C控制台。。。文本阅读、字数计算应用程序,c#,console-application,C#,Console Application,好的,我有一个C控制台应用程序,它被支持读取一个.txt文件…并计算不同的单词..它可以工作..但是我用一个100MB的文件来读取文件中每个不同的单词,它会持续几天。。 我想要的是一种方法,读取文件一次,并计算所有不同的单词。 以下是迄今为止该应用程序的一些示例: using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.T
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
using System.Data;
using System.IO.MemoryMappedFiles;
namespace CompressionApp
{
class Program
{
static void Main(string[] args)
{
//read all text
string FilePath = (@"D:\Test\testing.txt");
string FullText;
using (StreamReader streamReader = new StreamReader(FilePath))
{
FullText = streamReader.ReadToEnd();
}
FileInfo Info = new FileInfo(FilePath);
int FileSize = Convert.ToInt32(Info.Length);
//some code
string[] Words = FullText.Split(' ');
var DistinctWords = new List<string>(Words.Distinct());
//some code
int P = 0;
int ID = 0;
int Length = 0;
int ByteWorth;
double Perc;
double PPerc = 0;
bool display = false;
using (var mappedFile1 = MemoryMappedFile.CreateFromFile(FilePath))
{
using (Stream mmStream = mappedFile1.CreateViewStream())
{
using (StreamReader sr = new StreamReader(mmStream, ASCIIEncoding.ASCII))
{
Parallel.ForEach(DistinctWords, new ParallelOptions { MaxDegreeOfParallelism = 1 }, Word =>
{
DataRow dr = dt.NewRow();
string SearchTerm = Word;
var MatchQuery = from word in Words
where word == SearchTerm
select word;
int WordCount = MatchQuery.Count();
Length = SearchTerm.Length;
if (Length > 1)
{
if (WordCount > 1)
{
ID = ID + 1;
ByteWorth = (Length * 8) * WordCount;
dr["Word"] = SearchTerm;
dr["Count"] = WordCount;
dr["ID"] = ID;
dr["Length"] = Length;
dr["ByteWorth"] = ByteWorth;
dt.Rows.Add(dr);
}
}
//some code below
这是目前为止完整的应用程序…我知道不是很整洁。但我对编码还不熟悉
欢迎您提供任何提示、提示或建议。我无法为您编写完整的逻辑,但这里有一些提示。。 我用字典代替桌子。以后可以从字典中构建表。如果您想要id,请使用复杂值类型而不是“int”。该int值当前表示该字的计数数
var CheckedWords = new Dictionary<string, int>();
据我所知,你会得到不同的单词,然后对每个单词,你会通过整个文件来计算该单词的出现次数。我敢打赌,找到不同的单词只需要很短的时间,但计算出现次数的循环大约要花很长时间 您可以使用LINQ获得不同的单词及其计数。替换这一行代码:
var DistinctWords = new List<string>(Words.Distinct());
然后,您可以使用如下计数枚举单词:
foreach (var g in DistinctWithCount)
{
Console.WriteLine("{0},{1}", g.Word, g.Count);
}
你试过HashSet而不是List吗?var DistinctWords=new*HashSet*;var DistinctWords=new ListWords.Distinct之后您会做什么;你真的应该把这归结为一个真正的问题。请修复我的整个应用程序不是如此。我可以有一个指向示例文件的链接。请至少努力分离您的逻辑。我不会试图修复一个100多行的主方法来完成所有的事情。你似乎理解我的确切问题,我会尽快测试这段代码
var DistinctWithCount = from word in Words
group word by word
into g
select new {Word = g.Key, Count = g.Count()};
foreach (var g in DistinctWithCount)
{
Console.WriteLine("{0},{1}", g.Word, g.Count);
}