【发布时间】:2016-01-18 05:22:37
【问题描述】:
我试图将输入文件从句子标记为标记(单词)。 例如, “这是一个测试文件。”分成五个单词“this”“is”“a”“test”“file”,省略标点符号和空格。并将它们存储到数组列表中。 我试着写一些这样的代码:
public static ArrayList<String> tokenizeFile(File in) throws IOException {
String strLine;
String[] tokens;
//create a new ArrayList to store tokens
ArrayList<String> tokenList = new ArrayList<String>();
if (null == in) {
return tokenList;
} else {
FileInputStream fStream = new FileInputStream(in);
DataInputStream dataIn = new DataInputStream(fStream);
BufferedReader br = new BufferedReader(new InputStreamReader(dataIn));
while (null != (strLine = br.readLine())) {
if (strLine.trim().length() != 0) {
//make sure strings are independent of capitalization and then tokenize them
strLine = strLine.toLowerCase();
//create regular expression pattern to split
//first letter to be alphabetic and the remaining characters to be alphanumeric or '
String pattern = "^[A-Za-z][A-Za-z0-9'-]*$";
tokens = strLine.split(pattern);
int tokenLen = tokens.length;
for (int i = 1; i <= tokenLen; i++) {
tokenList.add(tokens[i - 1]);
}
}
}
br.close();
dataIn.close();
}
return tokenList;
}
这段代码运行良好,只是我发现它不是将整个文件变成几个单词(令牌),而是将整行变成一个令牌。 “area area”变成了一个token,而不是“area”出现了两次。我没有在我的代码中看到错误。我相信我的trim() 可能有问题。
任何有价值的建议表示赞赏。非常感谢。
也许我应该改用扫描仪??我很困惑。
【问题讨论】: