forked from srinathr91/TestJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPageTagger.java
More file actions
215 lines (184 loc) · 6.71 KB
/
PageTagger.java
File metadata and controls
215 lines (184 loc) · 6.71 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.StringEscapeUtils;
import edu.stanford.nlp.tagger.maxent.MaxentTagger;
/**
* Utility for tagging text (in the form of a String or a URL for a webpage),
* and tagging it with tokens indicating part-of-speech.
*
* @author chrchan
*/
public class PageTagger {
private static final String DEFAULT_MODEL =
"Taggers/english-left3words-distsim.tagger";
private static final String DEFAULT_USER_AGENT =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36";
private MaxentTagger tagger = null;
// the default chunk size in characters
private static final int DEFAULT_CHUNK_SIZE = 2000;
private static final int BUF_SIZE = 2048;
/**
* Main method that takes a single command-line argument of a URL whose
* content is to be tagged.
*
* @param argv
* URL whose content we want to tag
*/
public static void main(final String[] argv) {
URL url = null;
if (argv.length < 1) {
System.err.println("You need to give me a URL.");
System.exit(1);
}
try {
url = new URL(argv[0]);
} catch (MalformedURLException e) {
// bail, since there is nothing we can do at this point
e.printStackTrace();
System.exit(1);
}
PageTagger pageTagger = new PageTagger();
String text = null;
try {
text = pageTagger.getText(url);
} catch (Exception e) {
// bail, since there is nothing we can do at this point
e.printStackTrace();
System.exit(1);
}
String taggedText = pageTagger.tagText(text);
//System.out.println(taggedText);
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("result.txt"));
out.println(taggedText);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
out.close();
}
}
public PageTagger() {
tagger = new MaxentTagger(DEFAULT_MODEL);
}
/**
* Given a String, returns a new String where the text is tagged with tokens
* indicating part-of-speech.
*
* @param text
* the text that we want to tag
* @return a new String with tags
*/
public String tagText(final String text) {
// MaxentTagger does not like Unicode Replacement Character so strip it.
String cleanText = text.replaceAll("\uFFFD","");
// If text is too large, chunk it.
List<String> chunks = chunkText(cleanText);
StringBuilder sb = new StringBuilder();
for (String chunk : chunks) {
sb.append(tagger.tagString(chunk));
sb.append(" ");
}
return sb.toString();
}
/**
* Returns a String containing all the text in the body of a web page
* excluding HTML tags and JavaScript.
*
* @param url
* the location of the the web page to fetch the text of.
* @return String containing all the text in the body of a web page
* excluding HTML tags and JavaScript.
* @throws IOException
*/
public String getText(final URL url) throws IOException {
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", DEFAULT_USER_AGENT);
InputStream is = conn.getInputStream();
StringBuilder sb = new StringBuilder();
int bytesRead = 0;
try {
do {
byte[] b = new byte[BUF_SIZE];
bytesRead = is.read(b, 0, BUF_SIZE);
if (bytesRead != -1) {
sb.append(new String(b, 0, bytesRead));
}
} while (bytesRead != -1);
} catch (IOException ioe) {
throw ioe;
} finally {
is.close();
}
String ret = sb.toString();
ret = cleanText(ret);
return ret;
}
/**
* Cleans a String by removing thing that we do not consider text - scripts,
* tags, comments.
*
* @param s input String to clean
* @return a new String that is the old String with stuff removed
*/
private String cleanText(final String s) {
String ret = s;
// Remove scripts. The "(?s)" enables single-line mode so that newlines
// are included in the ".*" part of the pattern.
ret = ret.replaceAll("(?is)<script.*?/script>", " ");
// Remove anything in the head tag
ret = ret.replaceAll("(?is)<head.*?/head>"," ");
// Remove HTML comments.
ret = ret.replaceAll("(?s)<!--.*?-->", " ");
// Remove all tags.
ret = ret.replaceAll("<.*?>", " ");
// Unescape any escaped HTML entities.
ret = StringEscapeUtils.unescapeHtml4(ret);
return ret;
}
/**
* Breaks a String into chunks of at most DEFAULT_CHUNK_SIZE.
*
* @param largeText the String we want to break up
* @return a List of Strings
*/
private List<String> chunkText(final String largeText) {
List<String> chunks = new LinkedList<String>();
int totalSize = largeText.length();
int currentInd = 0;
while (currentInd < totalSize) {
int nextInd = currentInd + DEFAULT_CHUNK_SIZE - 1;
if (nextInd > totalSize) {
// we have reached the end
nextInd = totalSize - 1;
} else {
// We are somewhere in the middle of the document, so find a
// good place to separate. Look for a sentence boundary first.
int periodIndex = largeText.lastIndexOf('.', nextInd);
if ((periodIndex != -1) && (periodIndex > currentInd)) {
nextInd = periodIndex + 1;
} else {
// no sentence boundary, so try a word boundary
int wordIndex = largeText.lastIndexOf(' ', nextInd);
if ((wordIndex != -1) && (wordIndex > currentInd)) {
nextInd = wordIndex + 1;
}
}
// If no sentence or word boundary could be found, just break
// it at the chunk-size boundary.
}
String chunk = largeText.substring(currentInd, nextInd);
chunks.add(chunk);
currentInd = nextInd + 1;
}
return chunks;
}
}