09-TextProcessing-WordSegment-Case

4 hours ago 1

This article introduces how to use @kit.NaturalLanguageKit in HarmonyOS for text word segmentation and implement a simple sentiment analysis function. By creating a TextProcessingWordSegment component, users can input evaluation text, click a button to perform sentiment analysis, and finally display the sentiment tendency (positive, negative, or neutral) of the evaluation.

import { textProcessing } from '@kit.NaturalLanguageKit';

@Entry @Component struct TextProcessingWordSegment { @State comment: string = 'The logistics is fast, the packaging is good, and I am particularly satisfied with the product'; @State label: string = ''

build() { Column({ space: 20 }) { TextArea({ text: this.comment }) .height(200) Text('Evaluation Nature: ' + this.label) Button('Sentiment Analysis') .onClick(async () => { const results = await textProcessing.getWordSegment(this.comment) const words = results.map(item => item.word) const service = new SentimentAnalysisService() this.label = service.analyze(words) }) } .padding(15) .height('100%') .width('100%') }

}

// Sentiment Analysis Service Class class SentimentAnalysisService { private positiveWords = ['good', 'satisfied', 'great', 'excellent', 'fast']; private negativeWords = ['bad', 'slow', 'expensive', 'awful', 'unsatisfied'];

analyze(words: string[]) { let score = 0.5; words.forEach(word => { if (this.positiveWords.includes(word)) { score += 0.1; } if (this.negativeWords.includes(word)) { score -= 0.1; } }); score = Math.max(0, Math.min(1, score)); const label = score > 0.6 ? 'Positive' : score < 0.4 ? 'Negative' : 'Neutral'; return label; } }
Read Entire Article