【问题标题】:Tokens skip whitespace?令牌跳过空格?
【发布时间】:2012-04-10 02:24:43
【问题描述】:

好的,我已经问了另一个问题,我已经解决了这个问题,但这里是我想要做的事情的简要说明:我希望能够从文本文件中提取文本作为标记 - 例如,假设我有一个包含以下句子的文本文件:

这是一家不错的餐厅,

相信我!

我想将 this 的内容提取为 'tokens' - 例如,一个令牌将是“It's”,下一个令牌将是“”,之后的一个将是“a”,然后是“”,然后“好”,然后是“餐厅”,然后是“,”和“\n”,然后是“相信”、“”、“我”、“!”。所以我想一种说法是标记要么是单词,要么不是单词。

到目前为止,这是我的代码:

/**
* Returns the next token, or throws a NoSuchElementException if none remain.
*/
public Token next() {
  if (c == -1) {
        throw new NoSuchElementException();
    }

  Writer sw=new CharArrayWriter();
  boolean trf=false;
  try {
        while ( c != -1 && isWordCharacter(c) ) {
                sw.write(c);
                c = r.read();
                trf=true;
        }
        while ( c != -1 && !isWordCharacter(c)) {
            if (Character.isWhitespace(c)&&!(trf==true)){
                sw.write(c);
                c=r.read();
                }
            else if (Character.isWhitespace(c)&&(trf==true)){
                c=r.read();
            }
            else{
                sw.write(c);
                c = r.read();

            }
        }
    } catch (IOException e) {
        c = -1;
        return new Token(trf, sw.toString());
    }
    return new Token (trf, sw.toString());
} 

问题是我跳过了空格,所以我得到的是“It's”、“a”、“good”而不是“It's”、“”、“a”、“”、“good”等空格作为标记。有没有人有什么问题的提示?谢谢!

【问题讨论】:

    标签: java whitespace token


    【解决方案1】:

    这是reference的链接。
    StringTokenizer(String str, String delim, boolean returnDelims)

    正如最后一个参数所暗示的,它也会返回分隔符。

    StringTokenizer str = new StringTokenizer(sentence," \n\r",true);

    while(str.hasMoreTokens())
    {
        System.out.println(str.nextToken());
    }
    

    这应该给你你想要的。希望对您有所帮助。

    【讨论】:

    • 它会打印令牌和分隔符吗?
    • 是的,它也会打印分隔符,试一试。
    【解决方案2】:

    只要做:

    StringTokenizer str = new StringTokenizer(sentence);
    ArrayList<String> arr = new ArrayList<String>();
    while(str.hasMoreTokens())
    {
        //arr.add(" "); Be careful to add this only after the first word
        arr.add(str.nextToken());
    }
    

    在每个标记之后添加包含" " 的逻辑。它很简单;)

    【讨论】:

    • 不需要为包含token添加单独的逻辑,stringtokenizer为此提供了构造函数。
    猜你喜欢
    • 2015-01-28
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    相关资源
    最近更新 更多