题目描述
每一个网站都会根据访客日志统计访客数据,比如UV(Unique Visitor,即访问用户)。
UV能够回答一个关键的市场营销问题:“到底有多少人(潜在客户)看到了你发布的信息(即网站)”。
这道题的任务是根据给出的某购物网站访问日志,统计当天该网站UV。
日志文件的每一行代表一次访问行为,每行分别包含三项,以空格分隔,格式为:
用户访问的时间 用户的id 用户的行为
请问8月24号当天,该网站有多少个用户(相同用户id算一个用户)访问?
解法
package com.regex;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Visiter {
public static void main(String[] args) throws IOException {
String file_path = "tempfile//uv.txt";//存放文件的路径
String regex = " (\\d+) ";//设计正则表达式
File file = new File(file_path);
HashSet<String> set = getVister(file, regex);//用hashset去重
int count=0;
for(String id:set){
System.out.println("-"+id+"-");
count++;
}
System.out.println("count="+count);
}
public static HashSet<String> getVister(File file, String regex) throws IOException {
HashSet<String> set = new HashSet<String>();
// 1.读取文件
BufferedReader bufr = new BufferedReader(new FileReader(file));
// 2.将正则规则编译成对象。
Pattern p = Pattern.compile(regex);
String line = null;
while ((line = bufr.readLine()) != null) {
Matcher m = p.matcher(line);
while (m.find()) {
set.add(m.group());
}
}
bufr.close();
return set;
}
}