我一直在为此工作了几天,现在我无法取得任何进展。我尝试过使用Scanner和BufferedReader,但没有运气。使用BufferedReader翻译字符串(Java)
基本上,我有,需要一个String并缩短其工作方法(shortenWord)按照此格式的文本文件:“你好”
hello,lo
any,ne
anyone,ne1
thanks,thx
这也说明了这样的标点符号变成'lo?'等等。
我需要能够读取一个字符串并单独翻译每个单词,所以“你好?任何人都谢谢!”将变成“低级ne1 thx!”,基本上使用我已经拥有的字符串中每个单词的方法。我所拥有的代码将会翻译第一个单词,但对其他单词不起作用。我认为这与我的BufferedReader的工作方式有关。
import java.io.*;
public class Shortener {
private FileReader in ;
/*
* Default constructor that will load a default abbreviations text file.
*/
public Shortener() {
try {
in = new FileReader("abbreviations.txt");
}
catch (Exception e) {
System.out.println(e);
}
}
public String shortenWord(String inWord) {
String punc = new String(",?.!;") ;
char finalchar = inWord.charAt(inWord.length()-1) ;
String outWord = new String() ;
BufferedReader abrv = new BufferedReader(in) ;
// ends in punctuation
if (punc.indexOf(finalchar) != -1) {
String sub = inWord.substring(0, inWord.length()-1) ;
outWord = sub + finalchar ;
try {
String line;
while ((line = abrv.readLine()) != null) {
String[] lineArray = line.split(",") ;
if (line.contains(sub)) {
outWord = lineArray[1] + finalchar ;
}
}
}
catch (IOException e) {
System.out.println(e) ;
}
}
// no punctuation
else {
outWord = inWord ;
try {
String line;
while((line = abrv.readLine()) != null) {
String[] lineArray = line.split(",") ;
if (line.contains(inWord)) {
outWord = lineArray[1] ;
}
}
}
catch (IOException ioe) {
System.out.println(ioe) ;
}
}
return outWord;
}
public void shortenMessage(String inMessage) {
String[] messageArray = inMessage.split("\\s+") ;
for (String word : messageArray) {
System.out.println(shortenWord(word));
}
}
}
任何帮助,或者甚至在正确的方向微调将非常赞赏。
编辑:我试过在shortenWord方法结束时关闭了BufferedReader,它只是导致我在第一个表示BufferedReader关闭后的字符串中的每个单词出现错误。
在一个不相关的一面注:我想像这样的词缩写是任何英语老师的噩梦燃料。 – 2015-04-02 10:23:08
对于每个单词都一遍又一遍地阅读文件是毫无意义的,而且您实际上并没有这样做,因为一旦您达到文件末尾,如果您没有重新打开或倒带它,它将停留在文件的结尾。更好的逻辑是打开文件,读取一行,然后将替换应用到每个这样的行。 – RealSkeptic 2015-04-02 10:25:53
或将“翻译”读取到“Map”中。另外为什么你在使用'String punc = new String(“,?。!;”);'而不是'String punc =“,?。!;”;'? –
fabian
2015-04-02 10:33:00