-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordReplacer.java
More file actions
341 lines (321 loc) · 9.73 KB
/
Copy pathWordReplacer.java
File metadata and controls
341 lines (321 loc) · 9.73 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/*
* WordReplacer.java
*
* version 1.0 completed 4/13/2011
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* WordReplacer
*
* Utility class to replace a word in a .txt file, format the .txt file and
* create an HTML file of the re-formated .txt file
*
* @version 1.1
*
* Compiler: Java SE 1.8 OS: Windows 10 Hardware: PC
*
* April 13 2012 BVH completed v 1.0
* May 26 2016 BVH completed v 1.1
*/
public class WordReplacer {
private String fileName;
private String nameToReplace;
private String replacementName;
private File f;
private String[] book;
private int totalLines;
private int totalParagraphs;
private int totalSubstitutions;
private int paragraphsWithSubstitutions;
private static final int OFFSET = 4;
private final String pElement = "<p>";
//carriage feed to beautify doc
private final String closeP = "</p>\r\n";
private final String preElement = "<pre>";
private final String closePre = "</pre>";
private final String brElement = "<br />";
private final String newLine = "\r\n";
private boolean firstLine = true;
/**
* Default constructor
*
* @param fileName
* String representation of the .txt file
* @param replaceable
* String representation of the name to be replaced
* @param replacement
* String representation of the replacement name
*/
public WordReplacer(String fileName, String replaceable, String replacement) {
this.fileName = fileName;
nameToReplace = replaceable;
replacementName = replacement;
f = new File(fileName);
}
/**
* Method: makeArray() creates an arrayList from a .txt file and transfers
* the arrayList to a String array
*/
public void makeArray() {
ArrayList<String> theBook = scanTheBook();
book = new String[theBook.size()];
for (int i = 0; i < book.length; i++) {
book[i] = theBook.get(i);
}
totalLines = book.length;
}
private ArrayList<String> scanTheBook() {
ArrayList<String> theBook = new ArrayList<String>();
try {
Scanner bookScanner = new Scanner(f);
while (bookScanner.hasNextLine()) {
theBook.add(bookScanner.nextLine());
}
bookScanner.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(WordReplacer.class.getName()).log(Level.SEVERE, null, ex);
}
return theBook;
}
/**
* Method: replaceName() Uses regular expressions to replace the name given
* to be replaced with the name given for the replacement for each String in
* the aBook array
*/
public void replaceName() {
Pattern pattern = Pattern.compile("(?i)\\b" + nameToReplace + "(?i)");
paragraphsWithSubstitutions = 0;
totalSubstitutions = 0;
scanBook(pattern);
}
private void scanBook(Pattern pattern) {
for (int i = 0; i < book.length; i++) {
String bookLine = book[i];
Matcher matcher = pattern.matcher(bookLine);
if(matcher.find()){
paragraphsWithSubstitutions++;
matcher.reset();
countMatches(matcher);
book[i] = matcher.replaceAll(replacementName);
}
}
}
private void countMatches(Matcher matcher) {
while (matcher.find()) {
totalSubstitutions++;
}
}
/**
* Method: format() uses regular expressions to replace each occurrence of "
* with " in each String in the aBook array, then uses regular
* expressions to search for each occurrence of a blank String in the aBook
* array putting the Strings that are separated by blank lines into one
* String prefixed with
* <p>
* and postfixed with
* </p>
* , and adding that String to an arrayList it also uses regular expressions
* to find any String starting with 2 whitespace characters prefixing each
* String found with
*
* <pre>
* and postfixing it with
* </pre>
*
* The arrayList is copied to a String array and the ArrayList is set to
* null
*/
public void format() {
//note this was a requirement of the assignment and likely unnecessary
encodeQuoteChars();
doEncode();
totalParagraphs = book.length;
}
private void doEncode() {
ArrayList<String> bookInHTML = new ArrayList<String>();
Pattern whitespaceLine = Pattern.compile("^\\s*$");
Pattern twoWhitespaceChars = Pattern.compile("^\\s\\s");
Matcher wSLMatcher;
boolean specialFormat = false;
String temp = "";
for (int i = 0; i < book.length; i++) {
boolean found = false;
specialFormat = false;
found = false;
wSLMatcher = whitespaceLine.matcher(book[i]);
Matcher twoWSCMatcher = twoWhitespaceChars.matcher(book[i]);
if(twoWSCMatcher.find()) {
specialFormat = true;
}
if(wSLMatcher.find()) {
found = true;
}
if (!found && !specialFormat){
temp = addPLine(temp, firstLine, i);
}
else if (specialFormat && !found){
temp = addPreLine(temp, i);
}
else if (found && !specialFormat) {
//no open p element so just add a br
if(!temp.contains(pElement)){
bookInHTML = addBreak(temp, bookInHTML);
if(temp.contains(preElement)){
temp = "";
}
}
//close the p tag
else{
bookInHTML = closeTags(temp, bookInHTML);
temp = "";
}
}
else if(found && specialFormat){
//close pre tag
if(temp.contains(preElement)){
bookInHTML = closePreTag(temp, bookInHTML);
temp = "";
}
//close p tag
else if(temp.contains(pElement) && !temp.contains(closeP)){
bookInHTML = closePTag(temp, bookInHTML);
temp = "";
}
}
if (i == book.length - 1) {
if (temp.contains(pElement))
bookInHTML.add(temp + closeP);
if (temp.contains(preElement))
bookInHTML.add(temp + closePre);
}
}
book = new String[bookInHTML.size()];
for (int j = 0; j < bookInHTML.size(); j++) {
book[j] = bookInHTML.get(j);
}
bookInHTML = null;
}
private ArrayList<String> closePTag(String temp, ArrayList<String> bookInHTML) {
//beautify with newLine
temp += closeP + newLine;
bookInHTML.add(temp);
return bookInHTML;
}
private ArrayList<String> closePreTag(String temp, ArrayList<String> bookInHTML) {
//beautify with newLine
temp += closePre + newLine;
bookInHTML.add(temp);
//beautify with newLine
bookInHTML.add(brElement + newLine);
return bookInHTML;
}
private ArrayList<String> closeTags(String temp, ArrayList<String> bookInHTML) {
//check if we need to close pre tag
//close pre tag
if(temp.contains(preElement)){
//beautify with newLine
temp += closePre;
}
temp += closeP;
firstLine = false;
bookInHTML.add(temp);
return bookInHTML;
}
private ArrayList<String> addBreak(String temp, ArrayList<String> bookInHTML) {
//check if we need to close pre tag
//close pre tag
if(temp.contains(preElement)){
//beautify with newLine
temp += closePre + newLine;
bookInHTML.add(temp);
}
//add new line to make doc pretty
bookInHTML.add(brElement + newLine);
firstLine = !firstLine;
return bookInHTML;
}
private String addPreLine(String temp, int i) {
//we could also use a br tag but I think assignment specified using
//carriage return
if(!temp.contains(preElement))
temp += preElement + newLine + book[i] + newLine;
else
temp += book[i] + newLine;
return temp;
}
private String addPLine(String temp, boolean firstLine, int i) {
if(!temp.contains(pElement)){
temp += pElement + book[i] + " ";
firstLine = true;
}
else{
temp += book[i] + " ";
}
return temp;
}
private void encodeQuoteChars() {
Pattern pattern = Pattern.compile("\"");
Matcher matcher;
String replacement = """;
for (int i = 0; i < book.length; i++) {
String temp = book[i];
matcher = pattern.matcher(temp);
book[i] = matcher.replaceAll(replacement);
}
}
/**
* Method: createFile() Makes an HTML file of the .txt file, taking the
* original filename removing the .txt extension and appending
* _4_aReplacementName.html
*
* @param isLarge
* boolean signifying whether to use size 18 or 14 font
*/
public void createFile(boolean isLarge) {
fileName = fileName.substring(0, fileName.length() - OFFSET);
fileName += "_4_" + replacementName + ".html";
File modifiedBook = new File(fileName);
try {
PrintWriter fileOutput = new PrintWriter(new FileOutputStream(modifiedBook));
fileOutput.append(
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01" + " Transitional//EN\">\r\n<html>\r\n<head>\r\n"
+ "<meta http-equiv=" + "\"Content-Type\" content=\"text/html; "
+ "charset=us-ascii\">\r\n<title>the input file name + \" "
+ "for the replacement name</title>\r\n<style type = "
+ "\"text/css\">\t body {font-family: \"Times New Roman, " + "serif\"; font-size: ");
if (isLarge)
fileOutput.append("18;");
else
fileOutput.append("14;");
fileOutput.append("text-align: justify;};\tp { margin-left: 1%; "
+ "margin-right: 1%; }</style>\r\n</head>\r\n\r\n" + "<body>\r\n");
for (String paragraph : book) {
fileOutput.append(paragraph);
}
fileOutput.append("</body></html>");
fileOutput.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(WordReplacer.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Method: printInfo prints information about .txt and .html file
*/
public void printInfo() {
System.out.println("Star in Your Own Book! Ver. 1.0 By Bret A " + "Van Hof");
System.out.println("replace " + nameToReplace + " with " + replacementName);
System.out.println("file " + fileName + " created...");
System.out.println("original lines: " + totalLines);
System.out.println("total paragraphs: " + totalParagraphs);
System.out.println(totalSubstitutions + " replacements in " + paragraphsWithSubstitutions + " paragraphs");
}
}