我有一個過度使用的單詞的哈希圖作為鍵,它們的替換作為值。這是地圖中的一些值。
[令人驚嘆:令人驚訝的有趣:從字面上看很有趣:坦率地說很好:令人愉快的困難:征稅變化:轉變......]
我必須實作一個在給定文本檔案中搜索過度使用的單詞并用更好的選擇替換它們的類。 舊文本檔案:
” “太棒了”真的是我能想到的描述它的最好方式。從字面上看,我很難表達我有多喜歡它。真是太棒了!!!!!!好,還不錯。我不會改變"
新文本檔案:
” “令人驚訝”真的是我能想到的描述它的最佳方式。坦率地說,表達我有多喜歡它是很費力的。令人驚訝的愉快!!!!!!優越,而不是劣等。我不會改變一點點。請愉快地幫我修改我的寫作!!cat BB bbb Bb CAT"
- TextImprover 必須保留輸入檔案的標點符號。
- 假設輸入檔案中的所有單詞要么全部小寫,要么全部大寫,要么全部大寫。
我已經實作了第一個讀取 txt 檔案并制作過度使用單詞圖的函式:
public class TextImprover {
private HashMap<String, String> wordMap ;
/**
* Constructor
*
* @param wordMapFileName name of the file containing the over-used words and their replacements
*/
public TextImprover(String wordMapFileName) {
this.wordMap = new HashMap<String,String>();
try {
BufferedReader br = new BufferedReader(new FileReader(wordMapFileName));
String line ;
while((line = br.readLine())!= null) {
String[] wordLine = line.split("\t");
//System.out.println(wordLine[1]);
String overUsedWord = wordLine[0].trim();
String replaceWord = wordLine[1].trim();
wordMap.put(overUsedWord, replaceWord);
}
br.close();
}catch(FileNotFoundException e){
System.out.println("File: " wordMapFileName " not found");
}catch (IOException e1) {
System.out.println(e1.getMessage());
}
}
我需要這個功能:
/**
* Replaces all of the over-used words in the given file with better words, based on the word map
* used to create this TextImprover
*
* @param fileName name of the file containing the text to be improved
*/
public void improveText(String fileName) {
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line ;
while((line = br.readLine())!= null) {
String[] lineWords = line.split(" ");
// The code I'm strugling with
}
br.close();
}catch(FileNotFoundException e){
System.out.println("File: " fileName " not found");
}catch (IOException e1) {
System.out.println(e1.getMessage());
}
}
謝謝您的幫助。
uj5u.com熱心網友回復:
正如@HoRn 已經說過的,Stack Overflow 不是一個代碼撰寫服務,但我可以為您提供一些可能的解決方案的提示:
而不是split也使用正則運算式進行拆分的方法,我會[a-zA-Z] 以“通常”的方式使用正則運算式 () 來查找輸入中的下一個單詞。(“通常”的方式是使用 aPattern和 a Matcher。)
然后,您將使用將Matcher.replaceAll(Function<MatchResult,String> replacer)每個匹配項放入函式的方法,在那里您可以從地圖中獲取替換并決定是否要將其轉換為全部大寫或標題大小寫(僅第一個字符大寫)。
您發布的代碼的等效項(因此沒有實際的內部替換內容,但在那里更容易)看起來像這樣:
Pattern pattern = Pattern.compile("[a-zA-Z] "); // best outside the while loop!
// From here replaces your String[] lineWords = line.split(" "); inside the loop
Matcher matcher = pattern.matcher(line);
String result = matcher.replaceAll(match -> {
String word = match.group();
// TODO: find out if word is "ALL CAPS" or "Title Case"
// TODO: get replacement from map - don't forget to convert the input to the map toLowerCase()
String replacement = ...;
return replacement
});
// here your result contains the whole line with all replacements.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/530148.html
標籤:爪哇文件文本io
