jieba怎么自定义词典让”2023年9月1日“这种词time_pattern = re.compile(r'\d{4}[年\-]\d{1,2}[月\-]\d{1,2}[日号]?|\d{1,2}[时:]\d{1,2}[分:]?\d{0,2}[秒]?\b|\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}')能通过模板获取

时间: 2023-07-25 12:28:44 浏览: 40
如果想让`jieba`能够正确地识别出类似`20239月1日`这的时间关键词可以将其加入自定义词典中,并使用自定义的词性进行标注。 首先,我们需要时间关键词加入自定义词典中。例如,在自定义词典文件`my_dict.txt`中,可以添加以下内容: ``` 2023年9月1日 time ``` 其中,`time`是我们自定义的词性,用于标注时间关键词。保存后,可以使用`jieba.load_userdict()`方法将自定义词典文件加载进来: ```python import jieba jieba.load_userdict('my_dict.txt') ``` 接下来,在使用`jieba.cut()`方法分词时,可以使用`use_paddle=True`参数启用词性标注功能。这样,分词结果中就会包含词性信息。例如: ```python import jieba jieba.load_userdict('my_dict.txt') text = '我想知道2023年9月1日的天气' words = jieba.cut(text, use_paddle=True) for word, pos in zip(words, jieba.lcut(text, use_paddle=True)): print(word, pos) ``` 输出结果为: ``` 我 r 想 v 知道 v 2023年9月1日 time 的 u 天气 n ``` 可以看到,时间关键词`2023年9月1日`被正确地识别并标注为了自定义的词性`time`。 最后,我们可以使用正则表达式提取出所有词性为`time`的词汇,以获取时间关键词。例如: ```python import re import jieba jieba.load_userdict('my_dict.txt') text = '我想知道2023年9月1日的天气' words = jieba.cut(text, use_paddle=True) time_pattern = re.compile(r'time') results = [word for word, pos in zip(words, jieba.lcut(text, use_paddle=True)) if time_pattern.search(pos)] print(results) # ['2023年9月1日'] ``` 这样,我们就可以通过正则表达式获取到所有时间关键词了。

相关推荐

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 import torch from transformers import BertTokenizer, BertModel, BertConfig # 自定义词汇表路径 vocab_path = "output/user_vocab.txt" count = 0 with open(vocab_path, 'r', encoding='utf-8') as file: for line in file: count += 1 user_vocab = count print(user_vocab) # 种子词 seed_words = ['姓名'] # 加载微博文本数据 text_data = [] with open("output/weibo_data.txt", "r", encoding="utf-8") as f: for line in f: text_data.append(line.strip()) print(text_data) # 加载BERT分词器,并使用自定义词汇表 tokenizer = BertTokenizer.from_pretrained('bert-base-chinese', vocab_file=vocab_path) config = BertConfig.from_pretrained("bert-base-chinese", vocab_size=user_vocab) # 加载BERT模型 model = BertModel.from_pretrained('bert-base-chinese', config=config, ignore_mismatched_sizes=True) seed_tokens = ["[CLS]"] + seed_words + ["[SEP]"] seed_token_ids = tokenizer.convert_tokens_to_ids(seed_tokens) seed_segment_ids = [0] * len(seed_token_ids) # 转换为张量,调用BERT模型进行编码 seed_token_tensor = torch.tensor([seed_token_ids]) seed_segment_tensor = torch.tensor([seed_segment_ids]) model.eval() with torch.no_grad(): seed_outputs = model(seed_token_tensor, seed_segment_tensor) seed_encoded_layers = seed_outputs[0] jieba.load_userdict('data/user_dict.txt') # 构建隐私词库 privacy_words = set() privacy_words_sim = set() for text in text_data: words = jieba.lcut(text.strip()) tokens = ["[CLS]"] + words + ["[SEP]"] token_ids = tokenizer.convert_tokens_to_ids(tokens) segment_ids = [0] * len(token_ids) # 转换为张量,调用BERT模型进行编码 token_tensor = torch.tensor([token_ids]) segment_tensor = torch.tensor([segment_ids]) model.eval() with torch.no_grad(): outputs = model(token_tensor, segment_tensor) encoded_layers = outputs[0] # 对于每个词,计算它与种子词的余弦相似度 for i in range(1, len(tokens) - 1): word = tokens[i] if word in seed_words: continue if len(word) <= 1: continue sim_scores = [] for j in range(len(seed_encoded_layers)): sim_scores.append(torch.cosine_similarity(seed_encoded_layers[j][0], encoded_layers[j][i], dim=0).item()) cos_sim = sum(sim_scores) / len(sim_scores) print(cos_sim, word) if cos_sim >= 0.5: privacy_words.add(word) privacy_words_sim.add((word, cos_sim)) print(privacy_words) # 输出隐私词库 with open("output/privacy_words.txt", "w", encoding="utf-8") as f1: for word in privacy_words: f1.write(word + '\n') with open("output/privacy_words_sim.txt", "w", encoding="utf-8") as f2: for word, cos_sim in privacy_words_sim: f2.write(word + "\t" + str(cos_sim) + "\n") 详细解释上述代码,包括这行代码的作用以及为什么要这样做?

import jieba import torch from sklearn.metrics.pairwise import cosine_similarity from transformers import BertTokenizer, BertModel seed_words = ['姓名'] # 加载微博文本数据 text_data = [] with open("output/weibo1.txt", "r", encoding="utf-8") as f: for line in f: text_data.append(line.strip()) # 加载BERT模型和分词器 tokenizer = BertTokenizer.from_pretrained('bert-base-chinese') model = BertModel.from_pretrained('bert-base-chinese') seed_tokens = ["[CLS]"] + seed_words + ["[SEP]"] seed_token_ids = tokenizer.convert_tokens_to_ids(seed_tokens) seed_segment_ids = [0] * len(seed_token_ids) # 转换为张量,调用BERT模型进行编码 seed_token_tensor = torch.tensor([seed_token_ids]) seed_segment_tensor = torch.tensor([seed_segment_ids]) with torch.no_grad(): seed_outputs = model(seed_token_tensor, seed_segment_tensor) seed_encoded_layers = seed_outputs[0] jieba.load_userdict('data/userdict.txt') # 构建隐私词库 privacy_words = set() for text in text_data: words = jieba.lcut(text.strip()) tokens = ["[CLS]"] + words + ["[SEP]"] token_ids = tokenizer.convert_tokens_to_ids(tokens) segment_ids = [0] * len(token_ids) # 转换为张量,调用BERT模型进行编码 token_tensor = torch.tensor([token_ids]) segment_tensor = torch.tensor([segment_ids]) with torch.no_grad(): outputs = model(token_tensor, segment_tensor) encoded_layers = outputs[0] # 对于每个词,计算它与种子词的相似度 for i in range(1, len(tokens)-1): word = tokens[i] if word in seed_words: continue word_tensor = encoded_layers[0][i].reshape(1, -1) seed_tensors =seed_encoded_layers[0][i].reshape(1, -1) # 计算当前微博词汇与种子词的相似度 sim = cosine_similarity(word_tensor, seed_tensors, dense_output=False)[0].max() print(sim, word) if sim > 0.5 and len(word) > 1: privacy_words.add(word) print(privacy_words) 上述代码运行之后有错误,报错信息为:Traceback (most recent call last): File "E:/PyCharm Community Edition 2020.2.2/Project/WordDict/newsim.py", line 397, in <module> seed_tensors =seed_encoded_layers[0][i].reshape(1, -1) IndexError: index 3 is out of bounds for dimension 0 with size 3. 请帮我修改

import pandas as pd import matplotlib import numpy as np import matplotlib.pyplot as plt import jieba as jb import re from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_selection import chi2 import numpy as np from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB def sigmoid(x): return 1 / (1 + np.exp(-x)) import numpy as np #定义删除除字母,数字,汉字以外的所有符号的函数 def remove_punctuation(line): line = str(line) if line.strip()=='': return '' rule = re.compile(u"[^a-zA-Z0-9\u4E00-\u9FA5]") line = rule.sub('',line) return line def stopwordslist(filepath): stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()] return stopwords df = pd.read_csv('./online_shopping_10_cats/online_shopping_10_cats.csv') df=df[['cat','review']] df = df[pd.notnull(df['review'])] d = {'cat':df['cat'].value_counts().index, 'count': df['cat'].value_counts()} df_cat = pd.DataFrame(data=d).reset_index(drop=True) df['cat_id'] = df['cat'].factorize()[0] cat_id_df = df[['cat', 'cat_id']].drop_duplicates().sort_values('cat_id').reset_index(drop=True) cat_to_id = dict(cat_id_df.values) id_to_cat = dict(cat_id_df[['cat_id', 'cat']].values) #加载停用词 stopwords = stopwordslist("./online_shopping_10_cats/chineseStopWords.txt") #删除除字母,数字,汉字以外的所有符号 df['clean_review'] = df['review'].apply(remove_punctuation) #分词,并过滤停用词 df['cut_review'] = df['clean_review'].apply(lambda x: " ".join([w for w in list(jb.cut(x)) if w not in stopwords])) tfidf = TfidfVectorizer(norm='l2', ngram_range=(1, 2)) features = tfidf.fit_transform(df.cut_review) labels = df.cat_id X_train, X_test, y_train, y_test = train_test_split(df['cut_review'], df['cat_id'], random_state = 0) count_vect = CountVectorizer() X_train_counts = count_vect.fit_transform(X_train) tfidf_transformer = TfidfTransformer() X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts) 已经写好以上代码,请补全train和test函数

import jieba import pynlpir import numpy as np import tensorflow as tf from sklearn.model_selection import train_test_split # 读取文本文件 with open('1.txt', 'r', encoding='utf-8') as f: text = f.read() # 对文本进行分词 word_list = list(jieba.cut(text, cut_all=False)) # 打开pynlpir分词器 pynlpir.open() # 对分词后的词语进行词性标注 pos_list = pynlpir.segment(text, pos_tagging=True) # 将词汇表映射成整数编号 vocab = set(word_list) vocab_size = len(vocab) word_to_int = {word: i for i, word in enumerate(vocab)} int_to_word = {i: word for i, word in enumerate(vocab)} # 将词语和词性标记映射成整数编号 pos_tags = set(pos for word, pos in pos_list) num_tags = len(pos_tags) tag_to_int = {tag: i for i, tag in enumerate(pos_tags)} int_to_tag = {i: tag for i, tag in enumerate(pos_tags)} # 将文本和标签转换成整数序列 X = np.array([word_to_int[word] for word in word_list]) y = np.array([tag_to_int[pos] for word, pos in pos_list]) # 将数据划分成训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # 定义模型参数 embedding_size = 128 rnn_size = 256 batch_size = 128 epochs = 10 # 定义RNN模型 model = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_size), tf.keras.layers.SimpleRNN(rnn_size), tf.keras.layers.Dense(num_tags, activation='softmax') ]) # 编译模型 model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # 训练模型 model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, validation_data=(X_test, y_test)) # 对测试集进行预测 y_pred = model.predict(X_test) y_pred = np.argmax(y_pred, axis=1) # 计算模型准确率 accuracy = np.mean(y_pred == y_test) print('Accuracy: {:.2f}%'.format(accuracy * 100)) # 将模型保存到文件中 model.save('model.h5')出现下述问题:ValueError: Found input variables with inconsistent numbers of samples:

最新推荐

recommend-type

scrapy练习 获取喜欢的书籍

主要是根据网上大神做的 项目一 https://zhuanlan.zhihu.com/p/687522335
recommend-type

基于PyTorch的Embedding和LSTM的自动写诗实验.zip

基于PyTorch的Embedding和LSTM的自动写诗实验LSTM (Long Short-Term Memory) 是一种特殊的循环神经网络(RNN)架构,用于处理具有长期依赖关系的序列数据。传统的RNN在处理长序列时往往会遇到梯度消失或梯度爆炸的问题,导致无法有效地捕捉长期依赖。LSTM通过引入门控机制(Gating Mechanism)和记忆单元(Memory Cell)来克服这些问题。 以下是LSTM的基本结构和主要组件: 记忆单元(Memory Cell):记忆单元是LSTM的核心,用于存储长期信息。它像一个传送带一样,在整个链上运行,只有一些小的线性交互。信息很容易地在其上保持不变。 输入门(Input Gate):输入门决定了哪些新的信息会被加入到记忆单元中。它由当前时刻的输入和上一时刻的隐藏状态共同决定。 遗忘门(Forget Gate):遗忘门决定了哪些信息会从记忆单元中被丢弃或遗忘。它也由当前时刻的输入和上一时刻的隐藏状态共同决定。 输出门(Output Gate):输出门决定了哪些信息会从记忆单元中输出到当前时刻的隐藏状态中。同样地,它也由当前时刻的输入和上一时刻的隐藏状态共同决定。 LSTM的计算过程可以大致描述为: 通过遗忘门决定从记忆单元中丢弃哪些信息。 通过输入门决定哪些新的信息会被加入到记忆单元中。 更新记忆单元的状态。 通过输出门决定哪些信息会从记忆单元中输出到当前时刻的隐藏状态中。 由于LSTM能够有效地处理长期依赖关系,它在许多序列建模任务中都取得了很好的效果,如语音识别、文本生成、机器翻译、时序预测等。
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

【实战演练】MATLAB用遗传算法改进粒子群GA-PSO算法

![MATLAB智能算法合集](https://static.fuxi.netease.com/fuxi-official/web/20221101/83f465753fd49c41536a5640367d4340.jpg) # 2.1 遗传算法的原理和实现 遗传算法(GA)是一种受生物进化过程启发的优化算法。它通过模拟自然选择和遗传机制来搜索最优解。 **2.1.1 遗传算法的编码和解码** 编码是将问题空间中的解表示为二进制字符串或其他数据结构的过程。解码是将编码的解转换为问题空间中的实际解的过程。常见的编码方法包括二进制编码、实数编码和树形编码。 **2.1.2 遗传算法的交叉和
recommend-type

openstack的20种接口有哪些

以下是OpenStack的20种API接口: 1. Identity (Keystone) API 2. Compute (Nova) API 3. Networking (Neutron) API 4. Block Storage (Cinder) API 5. Object Storage (Swift) API 6. Image (Glance) API 7. Telemetry (Ceilometer) API 8. Orchestration (Heat) API 9. Database (Trove) API 10. Bare Metal (Ironic) API 11. DNS
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

【实战演练】时间序列预测用于个体家庭功率预测_ARIMA, xgboost, RNN

![【实战演练】时间序列预测用于个体家庭功率预测_ARIMA, xgboost, RNN](https://img-blog.csdnimg.cn/img_convert/5587b4ec6abfc40c76db14fbef6280db.jpeg) # 1. 时间序列预测简介** 时间序列预测是一种预测未来值的技术,其基于历史数据中的时间依赖关系。它广泛应用于各种领域,例如经济、金融、能源和医疗保健。时间序列预测模型旨在捕捉数据中的模式和趋势,并使用这些信息来预测未来的值。 # 2. 时间序列预测方法 时间序列预测方法是利用历史数据来预测未来趋势或值的统计技术。在时间序列预测中,有许多不
recommend-type

怎么在集群安装安装hbase

您好,关于如何在集群上安装HBase,步骤大致如下: 1. 在HBase官网上下载最新版本的HBase,并解压到需要安装的目录下; 2. 配置HBase的环境变量:将HBase目录的bin子目录加入到PATH环境变量中; 3. 修改HBase配置文件:在HBase目录下的conf子目录中找到hbase-site.xml文件,并进行相应的配置,如指定HBase的Zookeeper节点等; 4. 启动HBase:使用HBase的bin目录下的start-hbase.sh脚本启动HBase; 5. 验证HBase是否正常运行:使用HBase自带的shell命令行工具操作HBase。 注意:以上步