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;
}
}