DocumentParse.java
3.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package com.aigeo.util;
import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Pattern;
public class DocumentParse {
private final Tika tika;
// 定义有意义字符的正则表达式
private static final Pattern MEANINGFUL_CHAR_PATTERN = Pattern.compile("[\\s\\u4e00-\\u9fa5a-zA-Z0-9¥$€£¢₹₽₩₪₨₦₡₫₴₵₸₺₼₾₿.,;:'\"!?()-]*");
// 字符限制
private static final int CHINESE_CHAR_LIMIT = 30000;
private static final int ENGLISH_CHAR_LIMIT = 100000;
// 中文比例阈值
private static final double CHINESE_THRESHOLD = 0.4;
public DocumentParse() {
this.tika = new Tika();
}
// public String parse(InputStream inputStream) throws TikaException, IOException, DocumentParseException {
// // 使用Tika解析文档内容
// String rawContent = this.tika.parseToString(inputStream);
//
// // 过滤特殊字符,只保留有意义的字符
// String filteredContent = filterMeaningfulCharacters(rawContent);
//
// // 检查字符数是否超过限制
// validateContentLength(filteredContent);
//
// return filteredContent;
// }
/**
* 过滤特殊字符,只保留有意义的字符
* @param content 原始内容
* @return 过滤后的内容
*/
private String filterMeaningfulCharacters(String content) {
if (content == null || content.isEmpty()) {
return "";
}
// 使用正则表达式匹配有意义的字符
StringBuilder result = new StringBuilder();
java.util.regex.Matcher matcher = MEANINGFUL_CHAR_PATTERN.matcher(content);
while (matcher.find()) {
result.append(matcher.group());
}
return result.toString();
}
/**
* 验证内容长度是否超过限制
* @param content 过滤后的内容
* @throws DocumentParseException 当内容超过限制时抛出异常
*/
// private void validateContentLength(String content) throws DocumentParseException {
// if (content == null || content.isEmpty()) {
// return;
// }
//
// // 计算中文字符比例
// double chineseRatio = calculateChineseRatio(content);
//
// if (chineseRatio > CHINESE_THRESHOLD) {
// // 中文文档处理
// if (content.length() > CHINESE_CHAR_LIMIT) {
// throw new DocumentParseException("您的文档字符超过限制,请缩减文档再次上传");
// }
// } else {
// // 英文文档处理
// if (content.length() > ENGLISH_CHAR_LIMIT) {
// throw new DocumentParseException("您的文档字符超过限制,请缩减文档再次上传");
// }
// }
// }
/**
* 计算中文字符在总字符中的比例
* @param content 文档内容
* @return 中文字符比例
*/
private double calculateChineseRatio(String content) {
if (content == null || content.isEmpty()) {
return 0.0;
}
int totalChars = content.length();
int chineseChars = 0;
for (char c : content.toCharArray()) {
// 判断是否为中文字符(基本汉字范围)
if (c >= 0x4e00 && c <= 0x9fa5) {
chineseChars++;
}
}
return (double) chineseChars / totalChars;
}
}