re_error = re.compile()
时间: 2024-02-27 12:59:22 浏览: 25
在Python中,`re.compile()`是用于编译正则表达式的函数,可以将正则表达式字符串编译成一个正则表达式对象,以便于后面的正则表达式匹配操作使用。`re.compile()`函数接受一个正则表达式字符串作为参数,返回一个正则表达式对象。例如,如果要编译一个正则表达式字符串`'a*b+'`,可以使用以下代码:
```
import re
regex = re.compile('a*b+')
```
这将返回一个正则表达式对象,并赋值给`regex`变量。可以使用该对象进行正则表达式匹配操作。如果正则表达式字符串不合法,会抛出`re.error`异常。因此,如果不传递任何参数,会抛出`TypeError`异常,而不是`re.error`异常。
相关问题
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) 有什么问题 ,怎么解决
在 `doc2vec()` 函数中,你在尝试访问 `doc_id` 变量,但是该变量未定义,这会导致 `NameError` 错误。你需要将该变量定义为函数的参数,并在调用函数时传递文档的标识符。
另外,在 `doc2vec()` 函数中,你在尝试将 `Doc2Vec` 模型返回的向量赋值给 `vector` 变量,但是该变量没有使用,这会导致不必要的计算和内存占用。你应该直接返回模型返回的向量。
最后,在 `test_model()` 函数中,你在尝试打印向量的内存占用大小,但是你应该打印向量本身的大小,而不是指向向量的变量的大小。你可以使用 `np.ndarray.nbytes` 属性来获取向量的大小。
下面是修改后的代码:
```
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, doc_id):
start_alpha = 0.01
infer_epoch = 1000
doc = segment(codecs.open(file_name, 'r', 'utf-8').read())
return model.infer_vector(doc, alpha=start_alpha, steps=infer_epoch)
# 计算两个向量余弦值
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, doc_id=0) # 转成句子向量
vect2 = doc2vec(file2, model, doc_id=1)
print(vect1.nbytes) # 查看向量大小
print(vect2.nbytes)
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)
```
nfa = compiled_regex._pattern._compiler.compile() AttributeError: 're.Pattern' object has no attribute '_pattern'
这个错误通常是由于使用了Python 3.7或更高版本中的`re.compile()`函数的返回值(即`re.Pattern`对象),而不是旧版本中返回的`_sre.SRE_Pattern`对象。`_sre.SRE_Pattern`对象具有`_pattern`属性,而`re.Pattern`对象没有该属性。
解决这个问题的方法是使用旧版本的`re`模块,或者使用`re.compile()`函数的字符串模式作为参数,而不是将其结果存储在变量中。例如,可以尝试以下代码:
```
import re
regex = r'\d+'
nfa = re.compile(regex)._compiler.compile()
```
这将避免直接使用`re.Pattern`对象,并使代码更具可移植性。