在C#中对文本文件做情感倾向分析,核心步骤是先读取文件内容,再用情感词库进行匹配统计。下面介绍一种不依赖第三方机器学习框架的轻量实现方式。

一、读取文本文件
C#提供了多种读取文件的方法,最常用的是System.IO命名空间下的File类。对于不大的文本文件,可以直接使用File.ReadAllText把全部内容读成字符串。
using System;
using System.IO;
class Program
{
static void Main()
{
// 读取文本文件全部内容
string path = "C:\test\comment.txt";
string text = File.ReadAllText(path, System.Text.Encoding.UTF8);
Console.WriteLine("文件内容:" + text);
}
}
二、准备情感词库
我们可以用两个简单的列表来存放正向和负向词语。实际项目中词库可以放在文件或数据库中,这里先用数组演示。
using System.Collections.Generic;
List<string> positiveWords = new List<string> { "好", "喜欢", "满意", "棒", "推荐" };
List<string> negativeWords = new List<string> { "差", "讨厌", "失望", "烂", "退款" };
三、进行情感统计
读取到文本后,遍历词库并统计命中次数,就能算出正向与负向分数。
int posCount = 0;
int negCount = 0;
foreach (string word in positiveWords)
{
if (text.Contains(word))
{
posCount++;
}
}
foreach (string word in negativeWords)
{
if (text.Contains(word))
{
negCount++;
}
}
string result;
if (posCount > negCount)
{
result = "正面倾向";
}
else if (posCount < negCount)
{
result = "负面倾向";
}
else
{
result = "中性或无法判断";
}
Console.WriteLine("正向词数:" + posCount + ",负向词数:" + negCount);
Console.WriteLine("情感结果:" + result);
四、完整示例
把上面的逻辑组合成一个可运行的控制台程序:
using System;
using System.IO;
using System.Collections.Generic;
class Program
{
static void Main()
{
string path = "C:\test\comment.txt";
string text = File.ReadAllText(path, System.Text.Encoding.UTF8);
List<string> positiveWords = new List<string> { "好", "喜欢", "满意", "棒", "推荐" };
List<string> negativeWords = new List<string> { "差", "讨厌", "失望", "烂", "退款" };
int posCount = 0;
int negCount = 0;
foreach (string word in positiveWords)
{
if (text.Contains(word)) posCount++;
}
foreach (string word in negativeWords)
{
if (text.Contains(word)) negCount++;
}
string result = posCount > negCount ? "正面倾向" : (posCount < negCount ? "负面倾向" : "中性或无法判断");
Console.WriteLine("分析结果:" + result);
}
}
五、优化建议
- 使用分词库(如Jieba.NET)替代Contains,避免词语嵌套误判
- 为不同情感词设置权重,而不是简单计数
- 将词库外置为配置文件,方便维护
通过上述方式,C#可以很方便地读取文本文件并给出基础的情感倾向判断,适合日志评论筛查、简单反馈分类等场景。