我试图将输入文件从句子标记为标记(单词)。 例如, “这是一个测试文件。”分成五个单词“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;
}
这段代码工作正常,只是我发现它不是将整个文件分成几个单词( token ),而是将整行分成一个 token 。 “area面积”变成了一个token,而不是“area”出现了两次。我在我的代码中没有看到错误。我相信我的 trim()
可能有问题。
任何宝贵的建议将不胜感激。非常感谢。
也许我应该使用扫描仪?我很困惑。
最佳答案
我认为 Scanner 更适合这项任务。对于这段代码,您应该修复正则表达式,尝试 "\\s+";
关于java - 如何将一个文件分割成多个token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34847772/