我需要帮助创建一个循环,该循环将返回一个字符串,通过使用预定义的操作替换其中包含在hashmarks中的单词。这些包括getRandomElement,getPhrases和replace,都属于类“parserHelperImpl”。我到目前为止编写的代码如下。在单独的类中是此parserHelperImpl类中使用的代码。特别是我被困住的地方是创建一些东西来移动随机短语,这里命名为“原型”,并找到被哈希标记包围的单词。有关正则表达式的文档略高于我的消化级别。
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;
public class PhraseGeneratorFromFile implements PhraseGenerator {
private ParserHelperImpl parserHelper;
public PhraseGeneratorFromFile(String filename) {
// read file
StringBuilder fileContent = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader("corporate.txt"));
try {
String line = br.readLine();
while (line != null) {
fileContent.append(line);
fileContent.append('\n');
line = br.readLine();
}
String everything = fileContent.toString();
} finally {
br.close();
}
parserHelper = new ParserHelperImpl();
List<String> phraseCollection = parserHelper.getPhrases(fileContent,"phrases:");
String archetype = parserHelper.getRandomElement(phraseCollection);
}
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
public class ParserHelperImpl implements ParserHelper{
@Override
public List<String> getPhrases(StringBuilder fileContent, String token) {
StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(fileContent.toString()));
List<String> list = new ArrayList<String>();
try {
while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
if (tokenizer.sval.equals(token)) {
tokenizer.nextToken(); // '['
do {
tokenizer.nextToken(); // go to the number
list.add(String.valueOf(tokenizer.sval));
} while (tokenizer.nextToken() == ',');
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
@Override
public String replace(String templatePhrase, String token, String wordToPut) {
return templatePhrase.replace(token, wordToPut);
}
@Override
public String getRandomElement(List<String> list) {
double randnum = Math.random() * list.size();
int randindex = (int) randnum;
return list.get(randindex);
}
}
答案 0 :(得分:1)
您需要使用像#[^#]+#
这样的正则表来查找由哈希标记包围的单词。迭代匹配并替换每个匹配...大概你必须致电getRandomElement
来获取替换词。