Java 如何将文件拆分为多个令牌
我试图将输入文件从句子标记为标记(单词)。 例如 “这是一个测试文件。”五个字“这是一个测试文件”,省略了标点符号和空格。并将它们存储到arraylist中。 我试着写一些这样的代码:Java 如何将文件拆分为多个令牌,java,regex,io,token,trim,Java,Regex,Io,Token,Trim,我试图将输入文件从句子标记为标记(单词)。 例如 “这是一个测试文件。”五个字“这是一个测试文件”,省略了标点符号和空格。并将它们存储到arraylist中。 我试着写一些这样的代码: public static ArrayList<String> tokenizeFile(File in) throws IOException { String strLine; String[] tokens; //create a new ArrayList to sto
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;
}
publicstaticarraylisttokenizefile(文件位于)抛出IOException{
弦斯特林;
字符串[]标记;
//创建一个新的ArrayList来存储令牌
ArrayList tokenList=新的ArrayList();
if(null==in){
返回令牌列表;
}否则{
FileInputStream fStream=新的FileInputStream(in);
DataInputStream dataIn=新的DataInputStream(fStream);
BufferedReader br=新的BufferedReader(新的InputStreamReader(dataIn));
while(null!=(strLine=br.readLine()){
如果(strLine.trim().length()!=0){
//确保字符串独立于大小写,然后标记它们
strLine=strLine.toLowerCase();
//创建要拆分的正则表达式模式
//第一个字母为字母,其余字符为字母数字或'
字符串模式=“^[A-Za-z][A-Za-z0-9'-]*$”;
令牌=strLine.split(模式);
int tokenLen=tokens.length;
对于(int i=1;i我认为Scanner更适合此任务。对于此代码,您应该修复regex,尝试“\\s+”;
我认为Scanner更适合此任务。对于此代码,您应该修复regex,尝试“\\s+”;
尝试模式作为字符串模式=“[^\\w]”
在同一代码中尝试使用模式作为字符串模式=“[^\\w]”;
在同一代码中谢谢!!现在我知道我的正则表达式有些不寻常。谢谢!!现在我知道我的正则表达式有些不寻常。