所以我有一个100000字的文件。我想知道如何才能创建一个文件,其中包含“the:10282次”“and:322次”“sadfas222:1次”
这是文本文件的样子:
asdf
jkasdf
the
sadf
asdn
23kl
asdf
qer
f
asdf
r
2
r
fsd
fa
sdf
asd
far2
sdv
as
df
asdf
asdf
最佳答案
在 Node.js 中,执行 npm i split2 through2 -S
const fs = require('fs')
const split = require('split2')
const through = require('through2')
const words = {}
fs.createReadStream('words.txt')
.pipe(split())
.pipe(through(write, end))
function write (buf, enc, next) {
const word = buf.toString()
words[word] = ++words[word] || 1
next()
}
function end () {
Object.keys(words)
.sort((a, b) => words[b] - words[a])
.forEach(word => {
console.log(`${word}: ${words[word]} times`)
})
}
关于javascript - 如何将单词列表按照最常用到最不常用的顺序排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38948988/