以postgres数据库为例
1原始数据示例

2 处理数据,将需要识别文本前后特殊字符删除。
update 表名
set column1 = replace(replace(replace(column1,chr(9),''),chr(10),''),chr(13),''),
column2 = replace(replace(replace(column2,chr(9),''),chr(10),''),chr(13),'')
where 1 = 1;
3 连接数据库,读取数据进行处理
备注:
1 需要提前下载第三方包
第一步,打开cmd 终端
第二步:下载第三方包
pip install psycopg2
pip install psycopg2.extras
pip install spacy
pip install io
pip install time
pip install en_core_web_lg
en_core_web_sm、en_core_web_md和en_core_web_lg都是SpaCy自然语言处理库中的英语语言模型。
en_core_web_sm:该模型是SpaCy的默认英语模型,适用于小型项目和学术研究。该模型使用的词向量维度为50,包含了英语文本处理所需的基本信息,例如标点符号、词性标注、实体识别等。
en_core_web_md:该模型适用于中型项目和开发任务,其词向量维度为300,比en_core_web_sm更加精确。除了en_core_web_sm的所有功能外,en_core_web_md还可以提供更好的实体识别和句法分析。
en_core_web_lg:该模型是SpaCy最大的英语模型,适用于大型项目和商业应用,其词向量维度为700,提供了最全面的英语文本处理功能。除了en_core_web_md的所有功能外,en_core_web_lg还可以提供更好的词向量表示和词汇多样性,可以更好地处理多样化的英语文本。
总的来说,en_core_web_sm适合处理小型英语文本,en_core_web_md适合处理中型英语文本,en_core_web_lg适合处理大型英语文本。使用不同的模型取决于您的任务和数据规模。
2 需要在postgres 数据库新建一个存放数据的表格
CREATE TABLE 输出数据表名 (
id text NULL,
column1 text NULL,
brand_name text NULL
);
本次输出的数据形式是:

完整代码
import psycopg2
import psycopg2.extras
from config.load_config import get_connect_info
import spacy
import io
import time
class Link_Postgres():
def __init__(self):
conf1, conf2 = get_connect_info()
self.conn2 = psycopg2.connect(
dbname=数据库名,
user=用户名,
password=密码,
host=ip地址,
port=端口号
)
self.cur2 = self.conn2.cursor()
def match_title(self):
# 设置程序开始时间
start_time = time.time()
# 读取数据库的表
self.cur2.execute("SELECT id ,column1 ,column2 FROM 表名 ")
a_data = self.cur2.fetchall()
# 打印从数据库读取出来的数据
print(a_data)
# 加载英文模型
# 这里en_core_web_lg 可以替换成en_core_web_sm,en_core_web_md,使用不同的模型取决于您的任务和数据规模。
nlp = spacy.load("en_core_web_lg")
# 创建列表
new_record = []
# 遍历数据
for a_record in a_data:
# 拿出column1用nlp模型进行识别
doc = nlp(a_record[1])
# 遍历column1中的数据
for ent in doc.ents:
# 如果识别出品牌
if ent.label_ == "ORG":
# 将id,column1,识别出的品牌加载到new_data中
new_data = (a_record[0],a_record[1],ent.text)
print(f'识别出的column1中的品牌{new_data}')
# 将所有数据加载到列表中
new_record.append(new_data)
# 创建StringIO对象以保存数据
data_io = io.StringIO()
# 遍历所有识别出品牌的数据
for record in new_record:
# 当id,column1,识别出的品牌这三个字段同时存在时,
if len(record) == 3:
# 将数据写入StringIO对象中
data_io.write('\t'.join(record) + '\n')
# 表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。
data_io.seek(0)
# 使用copy_from方法将数据从StringIO对象复制到表
self.cur2.copy_from(data_io, 'm_title_20230317', sep='\t', columns=('url', 'html_title', 'brand_name'))
self.conn2.commit()
end_time = time.time()
print(f"数据已处理完成并入库,共耗时{end_time - start_time:.2f}秒")