import sys import re import jieba import codecs import gensim import numpy as np import pandas as pd def segment(doc: str): stop_words = pd.read_csv('data/stopwords.txt', index_col=False, quoting=3, names=['stopword'], sep='\n', encoding='utf-8') stop_words = list(stop_words.stopword) reg_html = re.compile(r'<[^>]+>', re.S) # 去掉html标签数字等 doc = reg_html.sub('', doc) doc = re.sub('[0-9]', '', doc) doc = re.sub('\s', '', doc) word_list = list(jieba.cut(doc)) out_str = '' for word in word_list: if word not in stop_words: out_str += word out_str += ' ' segments = out_str.split(sep=' ') return segments def doc2vec(file_name, model): start_alpha = 0.01 infer_epoch = 1000 doc = segment(codecs.open(file_name, 'r', 'utf-8').read()) doc_vec_all = model.infer_vector(doc, alpha=start_alpha, steps=infer_epoch) return doc_vec_all # 计算两个向量余弦值 def similarity(a_vect, b_vect): dot_val = 0.0 a_norm = 0.0 b_norm = 0.0 cos = None for a, b in zip(a_vect, b_vect): dot_val += a * b a_norm += a ** 2 b_norm += b ** 2 if a_norm == 0.0 or b_norm == 0.0: cos = -1 else: cos = dot_val / ((a_norm * b_norm) ** 0.5) return cos def test_model(file1, file2): print('导入模型') model_path = 'tmp/zhwk_news.doc2vec' model = gensim.models.Doc2Vec.load(model_path) vect1 = doc2vec(file1, model) # 转成句子向量 vect2 = doc2vec(file2, model) print(sys.getsizeof(vect1)) # 查看变量占用空间大小 print(sys.getsizeof(vect2)) cos = similarity(vect1, vect2) print('相似度:%0.2f%%' % (cos * 100)) if __name__ == '__main__': file1 = 'data/corpus_test/t1.txt' file2 = 'data/corpus_test/t2.txt' test_model(file1, file2)
时间: 2024-03-29 18:37:57 浏览: 192
这是一段 Python 代码,主要是使用 gensim 库实现了基于 Doc2Vec 模型的文本相似度计算。其中,首先使用 jieba 库对文本进行分词,并去除停用词,然后使用 gensim.models.Doc2Vec 中的 infer_vector 方法将文本转化为向量表示,最后使用余弦相似度计算两个向量之间的相似度。该代码中使用了两个测试文件 t1.txt 和 t2.txt,分别进行文本相似度计算,并输出相似度的结果。
相关问题
import pandas as pd import numpy as np import re import jieba import emoji import csv from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cluster import KMeans import pyLDAvis.gensim import nltk from collections import Counter import matplotlib.pyplot as plt import datetime # 转换时间用 from wordcloud import WordCloud, ImageColorGenerator from PIL import Image #import gensim from gensim import corpora import matplotlib.pyplot as plt import matplotlib import numpy as np import warnings from gensim.models import LdaModel import pyLDAvis.gensim warnings.filterwarnings('ignore')
从你的代码来看,你引入了许多与文本处理、自然语言处理(NLP)、聚类分析和可视化相关的库。这表明你可能正在处理一个涉及文本数据挖掘或主题建模的项目。以下是一些可能的应用场景及其实现方法:
### 场景:文本预处理
在进行文本分析之前,通常需要对文本进行清洗和分词。以下是实现文本清洗和分词的代码示例。
```python
def clean_text(text):
# 移除表情符号
text = emoji.demojize(text)
text = re.sub(r':\w+', '', text)
# 移除非中文字符
text = re.sub(r'[^\u4e00-\u9fa5]', ' ', text)
# 分词
words = jieba.lcut(text)
# 去停用词
stopwords = set(line.strip() for line in open('stopwords.txt', encoding='utf-8'))
words = [word for word in words if word not in stopwords and word != ' ']
return ' '.join(words)
# 示例应用
texts = ["我喜欢吃苹果", "今天天气真好"]
cleaned_texts = [clean_text(text) for text in texts]
print(cleaned_texts)
```
**解释**:
1. `emoji.demojize` 将表情符号转换为描述性文字。
2. 使用正则表达式移除非中文字符。
3. 使用 `jieba.lcut` 对文本进行分词。
4. 通过加载停用词表去除无意义的词汇(如“的”、“是”等)。
5. 最终将分词结果拼接成字符串返回。
---
### 场景:TF-IDF 特征提取
TF-IDF 是一种常用的文本特征提取方法,可以将文本转化为数值型特征向量。
```python
vectorizer = TfidfVectorizer(max_features=1000)
tfidf_matrix = vectorizer.fit_transform(cleaned_texts)
# 查看特征词汇
feature_names = vectorizer.get_feature_names_out()
print("TF-IDF 特征词汇:", feature_names[:10])
# 查看矩阵形状
print("TF-IDF 矩阵形状:", tfidf_matrix.shape)
```
**解释**:
1. `TfidfVectorizer` 将文本转化为 TF-IDF 特征矩阵。
2. `max_features=1000` 限制只保留最重要的 1000 个词汇。
3. `get_feature_names_out` 返回所有特征词汇。
4. `fit_transform` 生成稀疏矩阵表示文本特征。
---
### 场景:KMeans 聚类
基于 TF-IDF 特征矩阵,可以使用 KMeans 进行文本聚类。
```python
num_clusters = 3
kmeans = KMeans(n_clusters=num_clusters, random_state=42)
clusters = kmeans.fit_predict(tfidf_matrix)
# 输出每个文本所属的聚类
for i, cluster in enumerate(clusters):
print(f"文本 {i} 属于聚类 {cluster}")
```
**解释**:
1. `KMeans` 是一种无监督学习算法,用于将文本分为指定数量的簇。
2. `fit_predict` 根据特征矩阵计算每个文本所属的簇。
3. 通过调整 `num_clusters` 参数可以控制聚类的数量。
---
### 场景:LDA 主题建模
LDA 是一种常用的主题建模算法,可以发现文本中的潜在主题。
```python
# 将文本转化为词袋模型
dictionary = corpora.Dictionary([text.split() for text in cleaned_texts])
corpus = [dictionary.doc2bow(text.split()) for text in cleaned_texts]
# 训练 LDA 模型
num_topics = 2
lda_model = LdaModel(corpus, num_topics=num_topics, id2word=dictionary, passes=15)
# 输出主题
topics = lda_model.print_topics(num_words=5)
for topic in topics:
print(topic)
```
**解释**:
1. `corpora.Dictionary` 构建词典,将文本映射为整数 ID。
2. `doc2bow` 将文本转化为词袋表示。
3. `LdaModel` 训练 LDA 模型,`num_topics` 控制主题数量。
4. `print_topics` 输出每个主题及其对应的关键词。
---
### 场景:词云生成
词云是一种直观展示高频词汇的方法。
```python
all_words = ' '.join(cleaned_texts)
wordcloud = WordCloud(font_path='simhei.ttf', background_color='white').generate(all_words)
# 显示词云
plt.figure(figsize=(10, 6))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
```
**解释**:
1. `WordCloud` 生成词云图,`font_path` 指定中文字体路径。
2. `generate` 方法根据文本生成词云。
3. 使用 `matplotlib` 显示词云图。
---
### 总结
以上代码涵盖了文本预处理、特征提取、聚类分析、主题建模和可视化等多个方面。你可以根据具体需求选择合适的模块进行组合。
import pandas as pd import jieba from wordcloud import WordCloud import matplotlib.pyplot as plt from PIL import Image # 读取中间表数据并提取读者ID和图书ID列 df = pd.read_excel('中间表.xlsx') reader_ids = df['读者ID'] book_ids = df['图书ID'] # 根据读者ID和图书ID关联读者信息和图书目录,得到每个读者借阅的图书的书名 readers_info = pd.read_excel('读者信息.xlsx') books_catalog = pd.read_excel('图书目录.xlsx') books_borrowed = books_catalog[books_catalog['图书ID'].isin(book_ids)] borrowed_books_names = books_borrowed['书名'] # 使用jieba进行中文分词 split_words = [] for book_name in borrowed_books_names: words = jieba.lcut(book_name) split_words.extend(words) # 加载停用词表并进行停用词过滤 stop_words_files = ['停用词表1.txt', '停用词表2.txt', '停用词表3.txt'] stop_words = set() for stop_words_file in stop_words_files: with open(stop_words_file, 'r', encoding='utf-8') as f: stop_words |= set(f.read().splitlines()) filtered_words = [word for word in split_words if word not in stop_words] # 加载篮球形状图片并生成词云图 basketball_mask = np.array(Image.open('basketball.png')) wordcloud = WordCloud(font_path='simhei.ttf', background_color='white', mask=basketball_mask).generate(' '.join(filtered_words)) plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off') plt.show() # 获取词频最高的前10个词语 word_counts = pd.Series(filtered_words).value_counts() top_10_words = word_counts.head(10).index.tolist() print("该专业师生最迫切需要学习的知识:", top_10_words)
这段代码的作用是生成一个词云图,并输出该专业师生最迫切需要学习的知识(词频最高的前10个词语)。代码中使用了pandas库来读取和处理Excel文件数据,jieba库进行中文分词,wordcloud库生成词云图,matplotlib库进行图像展示,PIL库进行图片处理。
在代码中,使用`PIL.Image.open()`函数加载了一张名为'basketball.png'的图片作为词云图的形状模板。请确保'basketball.png'文件存在,并且与代码文件在同一目录下。
此外,代码还使用了一些Excel文件('中间表.xlsx'、'读者信息.xlsx'、'图书目录.xlsx'),请确保这些文件存在并包含正确的数据。
停用词表文件('停用词表1.txt'、'停用词表2.txt'、'停用词表3.txt')应该是包含一些常用词语的文本文件,每行一个词语。请确保这些文件存在,并且以UTF-8编码保存。
最后,代码输出了词频最高的前10个词语。请注意,此处涉及到`simhei.ttf`字体文件,确保该字体文件存在并与代码文件在同一目录下。
如果您遇到了任何错误,请提供具体的错误信息以便我更准确地帮助您解决问题。
阅读全文
相关推荐















