使用jieba进行数据预处理(分词,过滤停用词及标点,获取词频、关键词等)

整理停用词 去空行和两边的空格

#encoding=utf-8
filename = "stop_words.txt"

f = open(filename,"r",encoding='utf-8')
result = list()
for line in f.readlines():
    line = line.strip()
    if not len(line):
        continue

    result.append(line)
f.close
with open("stop_words2.txt","w",encoding='utf-8') as fw:
    for sentence in result:
        sentence.encode('utf-8')
        data=sentence.strip()  
        if len(data)!=0:  
            fw.write(data)
            fw.write("\n") 
print ("end")

分词、停用词过滤(包括标点)

#encoding=utf-8
import jieba
filename = "../data/1000页洗好2.txt"
stopwords_file = "../data/stop_words2.txt"

stop_f = open(stopwords_file,"r",encoding='utf-8')
stop_words = list()
for line in stop_f.readlines():
    line = line.strip()
    if not len(line):
        continue

    stop_words.append(line)
stop_f.close

print(len(stop_words))

f = open(filename,"r",encoding='utf-8')
result = list()
for line in f.readlines():
    line = line.strip()
    if not len(line):
        continue
    outstr = '' 
    seg_list = jieba.cut(line,cut_all=False) 
    for word in seg_list:  
        if word not in stop_words:  
            if word != '\t':  
                outstr += word 
                outstr += " "  
   # seg_list = " ".join(seg_list)
    result.append(outstr.strip())
f.close

with open("../data/test2.txt"
<think>嗯,用户让我介绍一下数据预处理到生成词云图的整个流程。首先,我需要确认用户的需求。他们可能在做文本分析的项目,需要处理中文评论数据,训练词向量,并提取关键词,最后可视化。用户可能对Python的库如pandas、gensim、jieba等有一定了解,但可能需要具体的步骤指导代码示例。 首先,数据预处理部分。用户提到用pandas读取数据,提取comment字段。这里需要注意数据格式,比如CSV或Excel,读取后是否正确提取。过滤停用词标点符号无意义字符,中文分词是关键。停用词表可能需要用户自己准备,或者使用现有的中文停用词资源。分词的话,jieba是常用的库,但用户可能需要处理特定领域的词汇,这时候自定义词典可能有帮助。另外,按评论ID输出预处理结果,可能需要将处理后的数据保存为DataFrame或文件,比如CSV。 然后是训练词向量模型。gensim的Word2Vec是常用的工具。需要确认评论数据是否已经分词,因为Word2Vec需要分好词的列表作为输入。参数设置如vector_size、window、min_count这些会影响模型效果,可能需要用户根据数据调整。保存模型后,后续步骤可能会用到。 接下来是提取关键词的三种方法。TF-IDFTextRank在jieba中已经有实现,但需要将文本转换为合适的格式。TF-IDF需要计算每个词的权重,取权重最高的五个词。TextRank是基于图排序的算法,同样取Top5。词向量聚类的话,可能需要先将评论中的词向量平均得到句子向量,然后用聚类算法如KMeans找出中心点附近的词。这部分可能比较复杂,尤其是如何从词向量到关键词,可能需要详细解释。 绘制词云图,需要将三种方法得到的关键词汇总,统计词频或用其他权重生成词云。wordcloud库可以处理中文,但需要注意字体路径的问题,避免中文显示为方框。词云图需要不同的颜色或样式来区分三种方法,可能需要用户调整参数。 用户可能的疑问点包括:如何处理分词中的专有名词,停用词表的获取,Word2Vec参数的选择,聚类方法的具体实现,以及词云图的中文显示问题。此外,代码示例中的路径文件可能需要用户根据实际情况修改,比如停用词文件的路径,数据文件的路径等。 还需要考虑代码的效率可扩展性。例如,处理大规模数据时,可能需要分批处理或使用更高效的分词工具。关键词提取的准确度可能受预处理效果影响,可能需要用户调整过滤条件或使用更复杂的模型。 最后,确保代码示例正确,语法无误,特别是LaTeX格式在回答中的使用,但根据用户的问题,可能不需要数学公式,所以系统级指令中的数学格式可能不适用,但需注意其他格式要求。整体结构要清晰,分步骤讲解,让用户能逐步跟进操作。</think>我将分步骤为您讲解完整实现流程,并提供关键代码示例: 一、数据预处理阶段 ```python import pandas as pd import jieba import re # 1. 读取数据 df = pd.read_csv('comments.csv') # 假设数据文件为CSV格式 comments = df[['comment_id', 'comment']] # 2. 加载停用词表 stopwords = set() with open('stopwords.txt', 'r', encoding='utf-8') as f: for line in f: stopwords.add(line.strip()) # 3. 预处理函数 def preprocess(text): # 去除非中文字符 text = re.sub(r'[^\u4e00-\u9fa5]', '', text) # 分词 words = jieba.lcut(text) # 过滤停用词 words = [w for w in words if w not in stopwords and len(w) > 1] return words # 4. 应用预处理 comments['processed'] = comments['comment'].apply(preprocess) # 5. 输出结果(示例) print(comments[['comment_id', 'processed']].head()) ``` 二、训练词向量模型 ```python from gensim.models import Word2Vec # 准备训练数据 sentences = comments['processed'].tolist() # 训练模型 model = Word2Vec( sentences, vector_size=100, # 向量维度 window=5, # 上下文窗口 min_count=3, # 最小词频 workers=4 ) # 保存模型 model.save("word2vec.model") ``` 三、关键词提取方法实现 1. TF-IDF方法 ```python from sklearn.feature_extraction.text import TfidfVectorizer # 将分词结果转为空格分隔字符串 comments['text'] = comments['processed'].apply(lambda x: ' '.join(x)) tfidf = TfidfVectorizer() tfidf_matrix = tfidf.fit_transform(comments['text']) # 获取每个评论的top5关键词 feature_names = tfidf.get_feature_names_out() tfidf_results = [] for i in range(len(comments)): feature_index = tfidf_matrix[i,:].nonzero()[1] scores = zip(feature_index, [tfidf_matrix[i, x] for x in feature_index]) sorted_scores = sorted(scores, key=lambda x: x[1], reverse=True) top5 = [feature_names[idx] for idx, _ in sorted_scores[:5]] tfidf_results.append(top5) ``` 2. TextRank方法 ```python from jieba import analyse # 设置TextRank参数 analyse.set_stop_words('stopwords.txt') tr = analyse.textrank textrank_results = [] for text in comments['comment']: keywords = tr(text, topK=5, withWeight=False) textrank_results.append(keywords) ``` 3. 词向量聚类方法 ```python from sklearn.cluster import KMeans import numpy as np # 生成评论向量(平均词向量) comment_vectors = [] for words in comments['processed']: vectors = [model.wv[word] for word in words if word in model.wv] if vectors: avg_vec = np.mean(vectors, axis=0) else: avg_vec = np.zeros(model.vector_size) comment_vectors.append(avg_vec) # K-means聚类 kmeans = KMeans(n_clusters=5) kmeans.fit(comment_vectors) # 获取每个聚类的中心词 cluster_keywords = {} for cluster_id in range(5): cluster_center = kmeans.cluster_centers_[cluster_id] # 查找最近的词 similar_words = model.wv.similar_by_vector(cluster_center, topn=10) cluster_keywords[cluster_id] = [w for w, _ in similar_words[:5]] # 为每个评论分配关键词 cluster_results = [] for label in kmeans.labels_: cluster_results.append(cluster_keywords[label]) ``` 四、词云图绘制 ```python from wordcloud import WordCloud import matplotlib.pyplot as plt def generate_wordcloud(keywords_list, title): all_words = ' '.join([' '.join(words) for words in keywords_list]) wc = WordCloud( font_path='SimHei.ttf', # 中文字体 background_color='white', max_words=50 ).generate(all_words) plt.imshow(wc) plt.title(title) plt.axis("off") plt.show() # 生成三种词云 generate_wordcloud(tfidf_results, 'TF-IDF关键词云') generate_wordcloud(textrank_results, 'TextRank关键词云') generate_wordcloud(cluster_results, '聚类关键词云') ``` 注意事项: 1. 需要准备的文件: - 中文停用词(stopwords.txt) - 中文字体文件(如SimHei.ttf) - 原始数据文件(comments.csv) 2. 扩展优化建议: - 添加自定义词典提高分词准确率 - 尝试不同词向量参数(size/window等) - 调整聚类数量方法 - 添加词云配色方案形状设置 3. 结果输出: - 预处理结果:DataFrame格式,包含comment_id预处理后的词列表 - 关键词结果:三个列表分别存储三种方法的结果 - 词云图:三个独立的可视化图表 这个流程实现了从原始数据到特征提取再到可视化的完整文本分析流程,可根据具体数据规模需求进行参数调整。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值