关于自然语言处理作业学到的新芝士
本项目使用python编写
数据处理
首先是使用with open语句,使用with读取能确保读取文件能在使用完成后关闭
with open('data\\virus_train.txt', 'r') as f:
对json格式的文件进行操作,目前只用了读取功能 。读取到的数据是多维字典或者是单维列表
data = json.load(f)
数据清洗方法函数,这里使用re.sub方法删除不需要的字符。使用正则表达式划定清洗目标
def clean_text(text):
text = re.sub(r'@[^\s]+:','',text)
text = re.sub(r'@[^\s]+ ','',text)
text = re.sub(r'\[[^\s]+\]','',text)
text = re.sub(r'【[^\s]+】','',text)
return text
补充:这种方法和某大佬的微博清洗对比,原文链接https://github.com/lovezxm/weibo-sentiment-analysis/blob/master/scripts/weiboOps.py
分词处理,lcut函数用于自动分割词语,对中文友好,我们python真的是太棒啦
segmented_texts = [" ".join(jieba.lcut(content)) for content in train_cleaned_contents]
一种多维数据表示方式
df_segmented = pd.DataFrame({
'Original Text': trian_contents,
'Cleaned Text': train_cleaned_contents,
'Segmented Text': segmented_texts,
'Label': trian_labels
})
print(df_segmented)
counter计数器
Counter 是 Python 标准库 collections 模块中的一个类,用于计数可哈希对象。它是一个字典的子类,其中元素作为键,它们的计数作为值。Counter 非常适合用于统计元素出现的频率。
计数元素频率: Counter 可以用来统计一个序列中每个元素出现的次数。例如,统计列表中每个单词的出现次数。
from collections import Counter
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_counts = Counter(words)
print(word_counts)
# 输出: Counter({'apple': 3, 'banana': 2, 'orange': 1})
词云生成方式
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 生成词云
word_counts = Counter(" ".join(segmented_texts).split())
wordcloud = WordCloud(font_path='simhei.ttf', # 设置字体路径以显示中文
width=800,
height=400,
background_color='white').generate_from_frequencies(word_counts)
# 显示词云
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
使用counter统计数量并用柱状图显示
# 使用 Counter 统计 label 的数量
label_counts = Counter(trian_labels)
# 提取 label 和对应的计数
labels, counts = zip(*label_counts.items())
# 绘制柱状图
plt.figure(figsize=(10, 5))
plt.bar(labels, counts)
plt.xlabel('Labels')
plt.ylabel('Counts')
plt.title('Label Counts')
plt.show()