【问题标题】:How to split a file into several tokens如何将文件拆分为多个令牌
【发布时间】: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() 可能有问题。 任何有价值的建议表示赞赏。非常感谢。

也许我应该改用扫描仪??我很困惑。

【问题讨论】:

    标签: java regex io token trim


    【解决方案1】:

    我认为 Scanner 更适合这项任务。至于这段代码,你应该修复正则表达式,试试"\\s+";

    【讨论】:

    • 谢谢!!现在我知道我的正则表达式有些不寻常。
    【解决方案2】:

    在同一代码中尝试模式为String pattern = "[^\\w]";

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      • 2016-10-26
      • 1970-01-01
      相关资源
      最近更新 更多