【发布时间】:2012-05-14 12:32:28
【问题描述】:
大家好,我在尝试使其正常工作时遇到问题。基本上我想要做的是读取一个包含此类数据的文本文件,但不完全是相似的,并计算每个字母出现在每一行的频率。真实数据还包含 0-255 之间的任何随机 ASCII。
一个例子是:
你好,我是约翰。
我们要 .4%2) &,.!米@ll
我想要的是在地图列表中实现的类似的东西
{H=3, i=3, ' '=3, t=1, h=2, s=2,...直到行尾},
{W=1, e=2, ' '=4, a=1, r=1, g=2, o=1, i=1, n=1, .=2, 4=1, % =1....直到行尾},
所以它是一个地图列表
我曾尝试研究类似的问题,但在编码方面我能做的最接近的是这个。
List <Map<String, Integer>> storeListsofMaps = new ArrayList<Map<String, Integer>>();
ArrayList <String> storePerLine = new ArrayList<String>();
String getBuf;
try {
FileReader rf = new FileReader("simpleTextCharDist.txt");
BufferedReader encapRF = new BufferedReader(rf);
getBuf = encapRF.readLine();
while (getBuf!=null){
storePerLine.add(getBuf);
getBuf = encapRF.readLine();
}
for (String index: storePerLine){
Map<String, Integer> storeCharAndCount = new HashMap<String, Integer>();
Integer count = storeCharAndCount.get(index);
storeCharAndCount.put(index, (count==null)?count = 1:count+1);
storeListsofMaps.add(storeCharAndCount);
}
System.out.println("StoreListsofMaps: "+ storeListsofMaps);
encapRF.close();
}
我知道这段代码不会执行我描述的代码,但一直坚持到这一部分。我显示的代码只会计算单词本身而不是字符串中的每个字母。我尝试通过将字符串转换为 char [] 并再次将其转换回字符串来计算对字符串中每个元素的迭代,但它的效率非常低并且会产生很多错误。希望有人能提供帮助。
【问题讨论】:
-
为什么不发布一个完整的类,在 main 方法中包含代码,并为所有变量提供类型?这样更容易修复它。
-
这是主要代码,因为我只是想了解如何解决问题。但除了我发布的代码之外,其他行只是声明和捕获表达式。
标签: java list maps character frequency