這個問題在這里已經有了答案: 使用 Javascript 查找字串中最常用的單詞? (7 個回答) 2天前關閉。
在這里完成 Javascript/Typescript 的新手。如何獲取包含標點符號的示例文本中最常見的 n 個單詞,例如
const sampleText = "hello world 這是 taco 這里是一些 foo bar 文本,用來向我在文本世界中的 tacos 世界問好,非常酷感謝 stackoverflow 今天是我的生日。這個文本還包含標點符號和我媽媽的車和“
我認為標點符號可以在事后從結果串列中過濾掉,如果這樣更容易的話
uj5u.com熱心網友回復:
顯然,您必須將那段文本分解成單詞。
然后您需要計算每個(唯一)單詞的出現次數。
什么是“詞”?嗯,最直截了當,它是空格之間的字符。
你提到你想忽略標點符號。
此外,您可能想忽略字母大小寫:“Hello”與“hello”是同一個詞。
一步步:
- 將整個字串轉換為小寫
let lowerText = sampleText.toLowerCase()
- 從字串中洗掉標點符號
使用正則運算式最容易做到這一點。這個洗掉了不是字母、數字或破折號的每個字符。它用空格替換任何其他字符。
let stringWithoutPunct = lowerText.replace(/[^a-zA-Z0-9-]/gi, ' ')
- 將那段文本分成單獨的單詞
let rawWords = stringWithoutPunct.split(' ')
請注意,如果字串中有任何位置有兩個連續的空格,這將導致一些“單詞”是空字串。我們將確保在后續步驟中忽略這些專案
- 生成唯一詞串列
let uniqueWords: Array<string> = []
for(let word of rawWords) {
// if this word is the empty string, ignore it
if(word === '') continue
// if this word is already on the list, ignore it
if(uniqueWords.includes(word)) continue
// otherwise, add this word to the list
uniqueWords.push(word)
}
- 計算每個單詞的出現次數
我們會將唯一單詞串列轉換為字典/哈希,其鍵是單詞,值是計數。
let countedWords: Record<string, number> = {}
for(let word of uniqueWords) {
let count = 0
// loop through the list of raw words, counting occurrences of this word
for(let rawWord of rawWords) {
if(rawWord === word) count = 1
}
// now store this word count pair in the dictionary
countedWords[word] = count
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/514850.html
上一篇:如何解決串列索引超出范圍的錯誤?
下一篇:如何檢查數獨中的每個3x3框?
