最近有个想法,想用编程实现:统计下面表中, 类别为主叫且号码是1的个数?
(该表在txt中存放)大家给个建议。
类别 号码
---------------------------------------------
主叫 1
被叫 2
主叫 1
被叫 2
主叫 1
被叫 2
主叫 1
被叫 2
主叫 1
被叫 1
主叫 1
被叫 2
主叫 1
被叫 2
被叫 2
被叫 2
被叫 2
被叫 2
被叫 1
被叫 2
被叫 1
被叫 1
被叫 1
主叫 1
主叫 1
主叫 1
主叫 2
主叫 2
主叫 2
主叫 2
(该表在txt中存放)大家给个建议。
类别 号码
---------------------------------------------
主叫 1
被叫 2
主叫 1
被叫 2
主叫 1
被叫 2
主叫 1
被叫 2
主叫 1
被叫 1
主叫 1
被叫 2
主叫 1
被叫 2
被叫 2
被叫 2
被叫 2
被叫 2
被叫 1
被叫 2
被叫 1
被叫 1
被叫 1
主叫 1
主叫 1
主叫 1
主叫 2
主叫 2
主叫 2
主叫 2
全局变量int count=0;
循环while(br.read()!=-1){
String temp = br.readLine();
if(temp.indexOf("主叫")>=0&&temp.indexOf("1")>=0){
count + =1;
}
}
下面是用java处理的结果10
public static void main(String[] args) throws IOException {
String file = "d:/t.txt";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8"));
Pattern p = Pattern.compile("^\\s*主叫\\s+1.*$");
int count = 0;
String line;
while((line = reader.readLine()) != null){
Matcher m = p.matcher(line);
if(m.find()){
count++;
}
}
reader.close();
System.out.println("count is :" + count);
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;public class CountString {
public static void main(String[] args) throws Exception {
int count=0;
String filedir=args[0];
System.out.println("filedir:"+filedir);
File file=new File(filedir);
FileInputStream fis=new FileInputStream(file);
InputStreamReader isr=new InputStreamReader(fis,"gb2312");
BufferedReader br=new BufferedReader(isr);
while(br.read()!=-1){
// System.out.println("读行");
String temp = br.readLine();
System.out.println("主叫位置:"+temp.indexOf("主叫"));
if(temp.indexOf("主叫")>=0&&temp.indexOf("1")>=0){
count+=1;
}
}
System.out.println("count:"+count);
}
}
Pattern p = Pattern.compile("^\\s*主叫\\s+1.*$");
怎么理解?
"^\\s*主叫\\s+1.*$" -- 这正则一旦数据有部分重复就会有问题
"^\\s*主叫\\s+1\\s*$" 1 写你要查询的号码