def Stop_words(): stopword = [] data = [] f = open('C:/Users/Administrator/Desktop/data/stopword.txt',encoding='utf8') for line in f.readlines(): data.append(line) for i in data: output = str(i).replace('\n','')#replace用法和sub函数很接近 stopword.append(output) return stopword # 采用jieba进行词性标注,对当前文档过滤词性和停用词 def Filter_word(text): filter_word = [] stopword = Stop_words() text = jieba.posseg.cut(text) for word, flag in text: if flag.startswith('n') is False:#用于检测字符串是否以指定的子字符串开始 continue if not word in stopword and len(word) > 1: filter_word.append(word) return filter_word # 对文档集过滤词性和停用词 def Filter_words(data_path =r'C:/Users/Administrator/Desktop/data//corpus.txt'): document = [] for line in open(data_path, 'r',encoding= 'utf8') : segment = jieba.posseg.cut(line.strip()) filter_words = [] stopword = Stop_words() for word, flag in segment: if flag.startswith('n') is False: continue if not word in stopword and len(word) > 1: filter_words.append(word) document.append(filter_words) return document def tf_idf(): tf_dict = {} idf_dict = {} filter_word = Filter_word(text) for word in filter_word: if word not in tf_dict: tf_dict[word] = 1 else: tf_dict[word] += 1 for word in tf_dict: tf_dict[word] = tf_dict[word] / len(text) document = Filter_words() doc_total = len(document) for doc in document: for word in set(doc): if word not in idf_dict: idf_dict[word] = 1 else: idf_dict[word] += 1 for word in idf_dict: idf_dict[word] = math.log(doc_total / (idf_dict[word] + 1)) tf_idf_dict = {} for word in filter_word: if word not in idf_dict: idf_dict[word] = 0 tf_idf_dict[word] = tf_dict[word] * idf_dict[word] return tf_idf_dict tf_idf_dict = tf_idf() keyword = 6 print('TF-IDF模型结果:') for key, value in sorted(tf_idf_dict.items(), key=operator.itemgetter(1),reverse=True)[:keyword]: print(key, end=' ') print('\n')

时间: 2024-03-28 17:38:58 浏览: 27
这段代码实现了一个 TF-IDF 模型,用于计算文本中关键词的权重。其中,Stop_words 函数用于读取停用词表,Filter_word 函数用于对单个文档进行过滤,Filter_words 函数用于对整个文档集进行过滤。tf_idf 函数用于计算 TF-IDF 值,最后输出了权重最高的前 keyword 个关键词。
相关问题

翻译代码def load_stopwords(file_path): stop_words = [] with open(file_path, encoding='UTF-8') as words: stop_words.extend([i.strip() for i in words.readlines()]) return stop_words def review_to_text(review): stop_words = load_stopwords(stopword_path) # 去除英文 review = re.sub("[^\u4e00-\u9fa5^a-z^A-Z]", '', review) review = jieba.cut(review) # 去掉停用词 if stop_words: all_stop_words = set(stop_words) words = [w for w in review if w not in all_stop_words] #print(words) return words

这段代码包含了两个函数: 1. load_stopwords(file_path):用于加载中文停用词表。具体实现步骤如下: a. 通过传入文件路径,利用with open的方式读取文件内容。 b. 将每行的停用词添加到stop_words列表中。 c. 返回stop_words列表。 2. review_to_text(review):用于将评论文本转换为文本列表。具体实现步骤如下: a. 调用load_stopwords函数,加载中文停用词表。 b. 使用正则表达式去除文本中的英文字符。 c. 使用jieba库进行中文分词。 d. 去除文本中的停用词。 e. 将处理后的文本列表作为函数返回值。 需要注意的是,这段代码使用了正则表达式去除了文本中的英文字符,只保留了中文字符。同时,在进行中文分词时,使用了jieba库。此外,对于停用词的处理,代码使用了Python中的列表推导式,将不在停用词表中的词语添加到words列表中。

import jieba def word_extract(): # 读取文件 corpus = [] path = 'D:/自然语言处理/第2章/data/金庸-白马啸西风.txt' content = '' for line in open(path, 'r', encoding='gbk', errors='ignore'): line = line.strip() content += line corpus.append(content) # 加载停用词 stop_words = [] path = 'D:/自然语言处理/第4章/data/stopword.txt' for line in open(path, encoding='utf8'): line = line.strip() stop_words.append(line) # jieba分词 split_words = [] word_list = jieba.cut(corpus[0]) for word in word_list: if word not in stop_words: split_words.append(word)这段代码哪里有问题

这段代码的缩进有问题,导致程序运行时会报错。具体来说,for循环和if语句的缩进应该向右移动一个制表符或四个空格,如下所示: ``` import jieba def word_extract(): # 读取文件 corpus = [] path = 'D:/自然语言处理/第2章/data/金庸-白马啸西风.txt' content = '' for line in open(path, 'r', encoding='gbk', errors='ignore'): line = line.strip() content += line corpus.append(content) # 加载停用词 stop_words = [] path = 'D:/自然语言处理/第4章/data/stopword.txt' for line in open(path, encoding='utf8'): line = line.strip() stop_words.append(line) # jieba分词 split_words = [] word_list = jieba.cut(corpus[0]) for word in word_list: if word not in stop_words: split_words.append(word) return split_words ```

相关推荐

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()) vector = model.docvecs[doc_id] return model.infer_vector(doc) # 计算两个向量余弦值 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) 有什么问题 ,怎么解决

import jieba from collections import Counter def read_dataset(path): labels = [] inputs = [] with open(path, 'r', encoding='utf-8') as file: for i, line in enumerate(file): line = line.strip() sample = line.split('\t') inputs.append(sample[0]) labels.append(sample[1]) return inputs, labels class MyDataset(): def init(self) -> None: self.vocab = {} self.stop_words = [] def set_stopword(self, path='data/scu_stopwords'): with open(path, 'r', encoding='utf-8') as fr: self.stop_words = [line.strip() for line in fr.readline()] def build_vocab(self, inputs, max_size='5000', min_freg=1): cnt = {} # 临时词典存储词频 for data in inputs: data = jieba.lcut(data) for word in data: if word not in cnt: cnt[word] = 1 else: cnt[word] += 1 cnt = sorted([_ for _ in cnt.items() if _[1]>=min_freg and _[0] not in self.stop_words], key=lambda t:t[1], reverse=True) self.vocab[''] = 0 if len(cnt) > max_size: i = 1 for w, _ in cnt: if len(self.vocab)>max_size: break self.vocab[w] = i i += 1 else: i = 1 for w, _ in cnt: self.vocab[w] = i i += 1 def transform(self, inputs, flag = 0): samples = [] iter = 0 for doc in inputs: if iter % 1000 == 0: print('-------%d------' % iter) doc = jieba.cut(doc) if flag==0: wordset = set(doc) # print(wordset) sample = [] for word in self.vocab.keys(): if word in wordset: sample.append(1) else: sample.append(0) elif flag == 1: sample = [0 for i in range(len(self.vocab.items()))] word_count = Counter(doc) for word in word_count.items(): if word[0] in self.vocab.keys(): id = self.vocab[word[0]] sample[id] = word[1] iter +=1 samples.append(sample) return samples def buid_tfidf_vocab(self, inputs, max_size): pass试着调参重构,提升精确率

import pandas as pd data = pd.read_csv(C:\Users\Administrator\Desktop\pythonsjwj\weibo_senti_100k.csv') data = data.dropna(); data.shape data.head() import jieba data['data_cut'] = data['review'].apply(lambda x: list(jieba.cut(x))) data.head() with open('stopword.txt','r',encoding = 'utf-8') as f: stop = f.readlines() import re stop = [re.sub(' |\n|\ufeff','',r) for r in stop] data['data_after'] = [[i for i in s if i not in stop] for s in data['data_cut']] data.head() w = [] for i in data['data_after']: w.extend(i) num_data = pd.DataFrame(pd.Series(w).value_counts()) num_data['id'] = list(range(1,len(num_data)+1)) a = lambda x:list(num_data['id'][x]) data['vec'] = data['data_after'].apply(a) data.head() from wordcloud import WordCloud import matplotlib.pyplot as plt num_words = [''.join(i) for i in data['data_after']] num_words = ''.join(num_words) num_words= re.sub(' ','',num_words) num = pd.Series(jieba.lcut(num_words)).value_counts() wc_pic = WordCloud(background_color='white',font_path=r'C:\Windows\Fonts\simhei.ttf').fit_words(num) plt.figure(figsize=(10,10)) plt.imshow(wc_pic) plt.axis('off') plt.show() from sklearn.model_selection import train_test_split from keras.preprocessing import sequence maxlen = 128 vec_data = list(sequence.pad_sequences(data['vec'],maxlen=maxlen)) x,xt,y,yt = train_test_split(vec_data,data['label'],test_size = 0.2,random_state = 123) import numpy as np x = np.array(list(x)) y = np.array(list(y)) xt = np.array(list(xt)) yt = np.array(list(yt)) x=x[:2000,:] y=y[:2000] xt=xt[:500,:] yt=yt[:500] from sklearn.svm import SVC clf = SVC(C=1, kernel = 'linear') clf.fit(x,y) from sklearn.metrics import classification_report test_pre = clf.predict(xt) report = classification_report(yt,test_pre) print(report) from keras.optimizers import SGD, RMSprop, Adagrad from keras.utils import np_utils from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.layers.embeddings import Embedding from keras.layers.recurrent import LSTM, GRU model = Sequential() model.add(Embedding(len(num_data['id'])+1,256)) model.add(Dense(32, activation='sigmoid', input_dim=100)) model.add(LSTM(128)) model.add(Dense(1)) model.add(Activation('sigmoid')) model.summary() import matplotlib.pyplot as plt import matplotlib.image as mpimg from keras.utils import plot_model plot_model(model,to_file='Lstm2.png',show_shapes=True) ls = mpimg.imread('Lstm2.png') plt.imshow(ls) plt.axis('off') plt.show() model.compile(loss='binary_crossentropy',optimizer='Adam',metrics=["accuracy"]) model.fit(x,y,validation_data=(x,y),epochs=15)

最新推荐

recommend-type

【图像压缩】 GUI矩阵的奇异值分解SVD灰色图像压缩【含Matlab源码 4359期】.zip

Matlab领域上传的视频均有对应的完整代码,皆可运行,亲测可用,适合小白; 1、代码压缩包内容 主函数:main.m; 调用函数:其他m文件;无需运行 运行结果效果图; 2、代码运行版本 Matlab 2019b;若运行有误,根据提示修改;若不会,私信博主; 3、运行操作步骤 步骤一:将所有文件放到Matlab的当前文件夹中; 步骤二:双击打开main.m文件; 步骤三:点击运行,等程序运行完得到结果; 4、仿真咨询 如需其他服务,可私信博主或扫描视频QQ名片; 4.1 博客或资源的完整代码提供 4.2 期刊或参考文献复现 4.3 Matlab程序定制 4.4 科研合作
recommend-type

node-v0.9.2-x86.msi

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

云原生架构与soa架构区别?

云原生架构和SOA架构是两种不同的架构模式,主要有以下区别: 1. 设计理念不同: 云原生架构的设计理念是“设计为云”,注重应用程序的可移植性、可伸缩性、弹性和高可用性等特点。而SOA架构的设计理念是“面向服务”,注重实现业务逻辑的解耦和复用,提高系统的灵活性和可维护性。 2. 技术实现不同: 云原生架构的实现技术包括Docker、Kubernetes、Service Mesh等,注重容器化、自动化、微服务等技术。而SOA架构的实现技术包括Web Services、消息队列等,注重服务化、异步通信等技术。 3. 应用场景不同: 云原生架构适用于云计算环境下的应用场景,如容器化部署、微服务
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这
recommend-type

数字舵机控制程序流程图

以下是数字舵机控制程序的流程图: ![数字舵机控制程序流程图](https://i.imgur.com/2fgKUQs.png) 1. 初始化引脚:设置舵机控制引脚为输出模式。 2. 初始化舵机:将舵机控制引脚输出的PWM信号设置为初始值,初始化舵机的位置。 3. 接收控制信号:通过串口或者其他方式接收舵机控制信号。 4. 解析控制信号:解析接收到的控制信号,确定舵机需要转动的角度和方向。 5. 转动舵机:根据解析后的控制信号,设置舵机控制引脚输出的PWM信号的占空比,使舵机转动到目标位置。 6. 延时:为了保证舵机转动到目标位置后稳定,需要延时一段时间。 7. 返回接收控制信