我有一个字符串
这是一个非常好的句子
我把它分成单独的单词并存储在String[]中:
String[] words = s.split(" ");如何对单词总数采取特定的百分比(比如说6个单词中的2个),并用其他内容替换这2个单词。 我的代码到目前为止:
//Indexes in total int maxIndex = words.length; //Percentage of total indexes double percentageOfIndexes = 0.20; //Round the number of indexes int NumOfIndexes = (int) Math.ceil( maxIndex * (percentageOfIndexes / 100.0)); //Get a random number from rounded indexes int generatedIndex = random.nextInt(NumOfIndexes);`I have a string like
This is a very nice sentence
I break it into separate words and store in String[] with:
String[] words = s.split(" ");How can I take a specific percentage on the total number of words (lets say 2 of 6 words) and substitute these 2 words with something else. My code so far:
//Indexes in total int maxIndex = words.length; //Percentage of total indexes double percentageOfIndexes = 0.20; //Round the number of indexes int NumOfIndexes = (int) Math.ceil( maxIndex * (percentageOfIndexes / 100.0)); //Get a random number from rounded indexes int generatedIndex = random.nextInt(NumOfIndexes);`最满意答案
首先,计算要替换的单词数:
int totalWordsCount = words.length; double percentageOfWords = 0.20; int wordsToReplaceCount = (int) Math.ceil( totalWordsCount * percentageOfWords );然后,知道要替换多少个单词,获取那么多随机索引,然后在这些索引处交换单词:
for (int i=0; i<wordsToReplaceCount; i++) { int index = random.nextInt(totalWordsCount); //and replace words[index] = "Other"; // <--- insert new words }注意:请记住,单词数量越少,您的百分比与要替换的实际单词数之间的差异就越大,例如。 6个单词中的20%是1.2个单词,在Math.ceil()之后变为2,并且从6开始变为2的33.33%。
First, calculate how many words you want to replace:
int totalWordsCount = words.length; double percentageOfWords = 0.20; int wordsToReplaceCount = (int) Math.ceil( totalWordsCount * percentageOfWords );Then, knowing how many words you want to replace, get that many random indexes, and just swap words at those indexes:
for (int i=0; i<wordsToReplaceCount; i++) { int index = random.nextInt(totalWordsCount); //and replace words[index] = "Other"; // <--- insert new words }NOTE: Just remember that the smaller the number of words, the bigger discrepancy between your percentage, and actual number of words to replace, eg. 20% from 6 words is 1.2 word, which becomes 2 after Math.ceil(), and 2 is 33.33% from 6.
更多推荐
发布评论