【发布时间】:2015-12-11 15:22:53
【问题描述】:
所以 - 我有两个代码可以用来在 java 中编写一个计算字符串中音节数的程序。代码是:
countSyllables(String word) 统计单个单词的音节数
getTokens(String pattern) 将字符串中的单词分成字符串列表
现在,我正在尝试使用这两个来计算字符串的音节数。爆炸是我的代码在最后两行有错误。您能否确定我获取音节数量的逻辑是否正确?以及如何改进我的代码以获得我想要的结果?
protected int countSyllables1(String doc)
{
//lower all the letters in the string
String inputString = doc.toLowerCase();
// put all the words of the string into a list of strings
List<String> WordTokens = getTokens("[a-zA-Z]+");
//convert the ArrayList to an Array
String[] WordTokensArr = new String[WordTokens.size()];
WordTokensArr = WordTokens.toArray(WordTokensArr);
//Iterate the array
for(String s: WordTokensArr)
{
//count the syllables
int SyllabCount = WordTokenArr.countSyllables(doc);
}
return SyllabCount;
}
这是我正在使用的帮助代码:
protected int countSyllables(String word) {
String input = word.toLowerCase();
int i = input.length() - 1;
int syllables = 0;
// skip all the e's in the end
while (i >= 0 && input.charAt(i) == 'e') {
i--;
syllables = 1;
}
boolean preVowel = false;
while (i >= 0) {
if (isVowel(input.charAt(i))) {
if (!preVowel) {
syllables++;
preVowel = true;
}
} else {
preVowel = false;
}
i--;
}
return syllables;
}
public boolean isVowel(char ch) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y') {
return true;
}
return false;
}
protected List<String> getTokens(String pattern)
{
ArrayList<String> tokens = new ArrayList<String>();
Pattern tokSplitter = Pattern.compile(pattern);
Matcher m = tokSplitter.matcher(text);
while (m.find()) {
tokens.add(m.group());
}
return tokens;
}
更新
CountSyllables1 方法已修改并且现在可以工作。它不能正确检测音节,但肯定会给出结果。
所以这就是我所做的更改: 1. 我将代码转移到另一个类,该类继承自包含 CountSyllables 和 getTokens 的类。我将方法的名称更改为 getNumSyllables()。 2. 该方法没有参数(String doc),我还删除了声明输入字符串的第一行和 toLowercase 方法,因为该方法已在 CountSyllables 类中使用。 3.迭代循环被修改,使得变量“result”被声明以帮助计数并返回音节的数量。
public int getNumSyllables()
{
// put all the words of the string into a list of strings
List<String> WordTokens = getTokens("[a-zA-Z]+");
//convert the ArrayList to an Array
String[] WordTokensArr = new String[WordTokens.size()];
WordTokensArr = WordTokens.toArray(WordTokensArr);
//Iterate the array
int result = 0;
for(String s: WordTokensArr)
{
//count the syllables and add to the result sum
result += countSyllables(s);
}
return result;
}
【问题讨论】:
-
“最后两行的错误” - 这些错误是什么?
-
public boolean isVowel之前缺少一个大括号,用于结束countSyllables方法 -
另外,上次我检查时,“y”不是元音
-
aeiou 有时是 y
-
Laleh H 请解释一下这段代码
WordTokenArr.countSyllables(doc);变量WordTokenArr的类型是什么?以及哪个类包含方法countSyllables
标签: java string arraylist count