保持计数和存储文本实例 [英] keeping count and storing of text instances
问题描述
我想创建一个简单的代码,计算txt文件中前三个最常用的行/文本,然后将该行/文本保存到另一个文本文件(这将被读入AutoCAD的变量系统)。
忘记我可以在VB.net中管理的AutoCAD零件,将3个最常用的文本行保存到自己的文本文件中,参见下面的示例:
要读取的文本文件内容如下:
APG
BTR
VTS
VTS
VTS
VTS
BTR
BTR
APG
PNG
程序将文本VTS保存到mostused.txt BTR到2ndmostused.txt和APG到3rdmostused.txt
如何才能最好地实现这一点?
由于我是C#开发人员,我会使用它:
var dict = new Dictionary< string,int>();
using(var sr = new StreamReader(file))
{
var line = string.Empty;
while((line = sr.ReadLine())!= null)
{
var words = line.Split(''); //得到单词
foreach(var word in words)
{
if(!dict.Contains(word))dict.Add(word,0);
dict [word] ++; // count them
}
}
}
var query = from d in dict select d order by d.Value; //现在你有它排序
int counter = 1;
foreach(查询中的var对)
{
使用(var sw = new StreamWriter(file+ counter +.txt))
sw.writer键);
}
I would like to make a simple code that counts the top three most recurring lines/ text in a txt file then saves that line/ text to another text file (this in turn will be read into AutoCAD’s variable system).
Forgetting the AutoCAD part which I can manage how do I in VB.net save the 3 most recurring lines of text each to its own text file see example below:
Text file to be read reads as follows:
APG BTR VTS VTS VTS VTS BTR BTR APG PNG
The VB.net program would then save the text VTS to mostused.txt BTR to 2ndmostused.txt and APG to 3rdmostused.txt
How can this be best achieved?
Since I'm C# developer, I'll use it:
var dict = new Dictionary<string, int>();
using(var sr = new StreamReader(file))
{
var line = string.Empty;
while ((line = sr.ReadLine()) != null)
{
var words = line.Split(' '); // get the words
foreach(var word in words)
{
if(!dict.Contains(word)) dict.Add(word, 0);
dict[word]++; // count them
}
}
}
var query = from d in dict select d order by d.Value; // now you have it sorted
int counter = 1;
foreach(var pair in query)
{
using(var sw = new StreamWriter("file" + counter + ".txt"))
sw.writer(pair.Key);
}
这篇关于保持计数和存储文本实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!