我有一个unix文本文件,我想在我的Android应用程序中阅读它,并将它分成句子。但是,我注意到BreakIterator将一些断行字符视为句子分隔符。我使用以下代码读取该文件并将其拆分为句子(仅输出第一句用于表示):
File file = new File...
String text = "";
BreakIterator sentenceIterator = BreakIterator.getSentenceInstance(Locale.US);
try {
FileInputStream inputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append('\n');
}
inputStream.close();
text = stringBuilder.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sentenceIterator.setText(text);
int end = sentenceIterator.next();
System.out.println(end);
System.out.println(text.substring(0, end));但是,如果我将Eclipse中的代码作为桌面应用程序编译并运行,文本就会被正确分割。我不明白它为什么在Android应用上不这么做。
我试图将文本文件转换为dos格式,甚至尝试读取该文件并保留原来的换行:
Pattern pat = Pattern.compile(".*\\R|.+\\z");
StringBuilder stringBuilder = new StringBuilder();
try (Scanner in = new Scanner(file, "UTF-8")) {
String line;
while ((line = in.findWithinHorizon(pat, 0)) != null) {
stringBuilder.append(line);
}
text = stringBuilder.toString();
sentenceIterator.setText(text);
int end = sentenceIterator.next();
System.out.println(end);
System.out.println(text.substring(0, end));
}但没有成功。有什么想法吗?您可以从以下文件(unix格式)下载节选:http://dropmefiles.com/TZgBp
我刚刚注意到它可以在不下载这个文件的情况下被复制。只需创建一个字符串,其中包含句子中的换行符(例如"Hello, \nworld!"),并运行一个检测测试。如果在通常的测试中使用BreakIterator,那么它将正确拆分。
我希望有两句话:
句子1:
前言 如果有同事对你说,今天晚上我的配偶在家里做了一顿不寻常的饭。
句子2:
你会加入吗?
是的,他们看起来不太好,但至少你知道为什么是这样的(句子分隔符是?等等)。但是,如果代码在Android上运行,它就会创建一个句子,即使是在
前言
出于某种原因..。
我不确定这是否是一个bug,或者是否有一个解决办法。但在我看来,这使得安卓版的BreakIterator作为句子拆分器毫无用处,因为书籍中的句子在多行之间传播是正常的。
在所有的实验中,我使用了相同的import java.text.BreakIterator;
发布于 2018-01-23 09:53:31
这不是一个真正的答案,但它可能会给你一些洞察力。
这不是一个文件编码问题,我尝试了他的方式,并有同样的错误行为。
BreakIterator sentenceIterator = BreakIterator.getSentenceInstance(Locale.US);
String text = "Foreword\nIf a colleague were to say to you, Spouse of me this night today manufactures the unusual meal in a home. You will join?";
sentenceIterator.setText(text);Android不使用与您的计算机相同的Java版本
我注意到当我打印出sentenceIterator对象的类时
sentenceIterator.getClass()在使用IntelliJ运行和在Android上运行时,我有不同的类:
使用IntelliJ运行:
sun.util.locale.provider.RuleBasedBreakIterator运行在Android上:
java.text.RuleBasedBreakIterator sun.util.locale.provider.RuleBasedBreakIterator有你想要的行为。
我不知道如何让安卓使用好的RuleBasedBreakIterator类。我甚至不知道这是否可能。
https://stackoverflow.com/questions/48383331
复制相似问题