我将文本作为 String
并需要计算每个单词中的音节数。我试图将所有文本拆分为单词数组,然后分别处理每个单词。我为此使用了正则表达式。但是音节模式不能正常工作。请建议如何更改它以计算正确的音节数。我的初始代码。
public int getNumSyllables()
{
String[] words = getText().toLowerCase().split("[a-zA-Z]+");
int count=0;
List <String> tokens = new ArrayList<String>();
for(String word: words){
tokens = Arrays.asList(word.split("[bcdfghjklmnpqrstvwxyz]*[aeiou]+[bcdfghjklmnpqrstvwxyz]*"));
count+= tokens.size();
}
return count;
}
最佳答案
这道题来自加州大学圣地亚哥分校的Java类(class),我说的对吗?
我认为你应该为这个问题提供足够的信息,这样才不会让想提供帮助的人感到困惑。在这里,我有自己的解决方案,已经通过本地程序的测试用例和 UCSD 的 OJ 进行了测试。
您错过了有关此问题中音节定义的一些重要信息。 其实我认为这个问题的关键点是你应该如何处理e
。例如,假设有te
的组合.而如果把te
放在一个词的中间,当然应该算作一个音节;但是,如果它位于单词的末尾,则 e
应该被认为是英语中的 silent e
,因此不应将其视为音节。
就是这样。我想用一些伪代码写下我的想法:
if(last character is e) {
if(it is silent e at the end of this word) {
remove the silent e;
count the rest part as regular;
} else {
count++;
} else {
count it as regular;
}
}
你可能会发现我不只是使用正则表达式来处理这个问题。其实我也想过:这道题真的只能用正则来做吗?我的回答是:不,我不这么认为。至少现在,以加州大学圣地亚哥分校给我们的知识,要做到这一点太难了。正则表达式是一个强大的工具,它可以非常快速地映射出想要的字符。但是正则表达式缺少一些功能。还是以te
为例,正则表达式在面对teate
这样的词时是不会三思的(这个词是我编造的)。如果我们的正则表达式模式将第一个 te
计为音节,那么为什么最后一个 te
不是?
同时,UCSD其实已经在assignment paper上谈到了:
If you find yourself doing mental gymnastics to come up with a single regex to count syllables directly, that's usually an indication that there's a simpler solution (hint: consider a loop over characters--see the next hint below). Just because a piece of code (e.g. a regex) is shorter does not mean it is always better.
这里的提示是,你应该把这个问题和一些循环结合起来,结合正则表达式来思考。
好的,我现在终于可以展示我的代码了:
protected int countSyllables(String word)
{
// TODO: Implement this method so that you can call it from the
// getNumSyllables method in BasicDocument (module 1) and
// EfficientDocument (module 2).
int count = 0;
word = word.toLowerCase();
if (word.charAt(word.length()-1) == 'e') {
if (silente(word)){
String newword = word.substring(0, word.length()-1);
count = count + countit(newword);
} else {
count++;
}
} else {
count = count + countit(word);
}
return count;
}
private int countit(String word) {
int count = 0;
Pattern splitter = Pattern.compile("[^aeiouy]*[aeiouy]+");
Matcher m = splitter.matcher(word);
while (m.find()) {
count++;
}
return count;
}
private boolean silente(String word) {
word = word.substring(0, word.length()-1);
Pattern yup = Pattern.compile("[aeiouy]");
Matcher m = yup.matcher(word);
if (m.find()) {
return true;
} else
return false;
}
您可能会发现,除了给定的方法 countSyllables
之外,我还创建了两个额外的方法 countit
和 silente
。 countit
用于计算单词中的音节,silente
试图找出该单词以无声 e
结尾。并且还需要注意的是not silent e
的定义。例如,the
应该被认为是 not silent e
,而 ate
被认为是 silent e
。
这是我的代码已经通过测试的状态,来自本地测试用例和来自 UCSD 的 OJ:
以及来自OJ的测试结果:
P.S:直接使用[^aeiouy]之类的应该没问题,因为在我们调用这个方法之前已经解析了这个词。还需要更改为小写,这样可以节省大量处理大写的工作。我们想要的只是音节数。
说到number,一个比较优雅的方式是将count
定义为static,这样private方法就可以直接在里面调用count++
了。不过现在好了。
如果还是不懂这道题的方法,欢迎随时联系我:)
关于java - 如何使用正则表达式和 Java 计算文本中的音节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33425070/