我的函数遍历文本中的短语并显示在文本中至少出现一次的所有短语。我没有找到一种方法来不显示在文本中只出现一次的短语。
function toPhrases(text, wordCount) {
const words = text.match(/[\w\u0402-\u045f]+/ig)
const phrases = new Map()
for (let i = 0; i < words.length; i++) {
let phrase = words.slice(i, i + wordCount).join(' ')
let hashedPhrases = phrases.get(phrase)
if (hashedPhrases) {
phrases.set(phrase, hashedPhrases + 1)
} else {
phrases.set(phrase, 1)
}
if (i + wordCount >= words.length) {
break
}
}
return phrases
}
function createPhrases() {
const text = document.getElementById('textarea').value;
document.getElementById('output-2').innerHTML = JSON.stringify([...toPhrases(text.toString(), 2)]);
document.getElementById('output-3').innerHTML = JSON.stringify([...toPhrases(text.toString(), 3)]);
document.getElementById('output-4').innerHTML = JSON.stringify([...toPhrases(text.toString(), 4)]);
}
最佳答案
这应该有效:
function toPhrases(text, wordCount){
const words = text.match(/[\w\u0402-\u045f]+/ig)
const groups = words.reduce((acc, w) => {
acc[w] = (acc[w] + 1) || 1;
return acc;
}, {});
// group is an object where keys are all the words and values are the occurrence of that word
// now filter to get all the words that has only one occurrence
return Object.keys(groups).filter(k => groups[k] === 1)
}
关于javascript - 如何不显示字符串中只出现一次的短语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59499938/