所以 - 我得到了两个代码,以便用 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;
}
最佳答案
最后,您遍历单词以计算音节数:
for(String s: WordTokensArr) {
int SyllabCount = WordTokenArr.countSyllables(doc);
}
return SyllabCount;
变量 SyllabCount
无法在 for 循环之外访问。即使您在循环之前声明它,您也会覆盖每个单词的值。相反,添加每个单词的音节数:
int SyllabCount = 0; // Start with 0.
for(String s: WordTokensArr) {
// Add the amount from this word
SyllabCount = SyllabCount + WordTokenArr.countSyllables(s);
}
return SyllabCount;
关于Java - 计算大字符串中的音节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34226874/