【发布时间】:2023-03-17 11:45:01
【问题描述】:
对于包含如下语句的文件:
He O O
does O O
, O O
however O O
, O O
have B-MWE_LVC B-MWE_LVC_VERB
an I-MWE_LVC O
affair I-MWE_LVC B-MWE_LVC_NOUN
with O O
Clotho B-NE_PER O
, O O
the O O
youngest O O
aspect O O
of O O
Fate B-NE_MISC B-NE_MISC_SB
. O O
This O O
is O O
both O O
awkward O O
and O O
intriguing O O
to O O
Norton B-NE_PER O
since O O
her O O
past O O
is O O
his O O
future B-SENT_BOUND O
. O O
我想根据标记每个句子结尾的正则表达式模式 (.o o) 提取每个句子。我在下面写了一些代码来解析它,但得到一个错误
线程“主”java.lang.StringIndexOutOfBoundsException 中的异常: 字符串索引超出范围:-1 在 java.lang.String.substring(未知 来源)在 com.gyan.siapp.coref.resolve.test.main(test.java:46)
第 46 行是:builder.append(strLine.substring(0, strLine.indexOf(' ')));
我的代码:
public static void main(String args[]) {
StringBuilder builder = new StringBuilder();
String folderPath ="C:/Users/Desktop/Data_And_Sentences/wiki50.iob";
Scanner file = null;
try
{
file = new Scanner(new File(folderPath));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
List<String> sentences = new ArrayList<String>();
String strLine;
//Read File Line By Line
Pattern matchExp = Pattern.compile ("(.*?)(. O O)");
Matcher m = matchExp.matcher(strLine);
while (file.hasNext())
{
while (!m.find()){
builder.append(strLine.substring(0, strLine.indexOf(' ')));
builder.append(" ");
}
sentences.add(builder.toString());
}
System.out.println(sentences);
//return sentences;
}
这是正确的方法吗?我应该使用 String Builder 以外的其他结构来确保足够的内存吗?我的猜测是整个文件被作为一个字符串读取,因此我得到了这个异常。对吗?
【问题讨论】:
-
不要每次都重新编译模式,你只需要在循环外这样做一次。此外,如果您需要帮助发布完整的堆栈跟踪并指出代码中的哪个语句引发了异常。
-
@JimGarrison 根据您的建议编辑了代码,并提供了完整的错误描述。谢谢。
-
如果有匹配项,您的意思是要将内容附加到
builder吗?删除!然后while (m.find()){ -
我强烈建议您在调试器中一次单步执行代码以了解它在做什么。