python倒排索引_如何更快地建立倒排索引?

博主正在尝试使用Python构建一个简单的搜索引擎,通过爬虫抓取的数据存储在MySQL,接着进行分词并构建倒排索引。目前的实现方式是在内存中使用字典暂存,再将索引存入Redis。遇到的问题是当前方法耗时较长,期待优化算法。代码中利用jieba分词并过滤停用词,将单词与对应网页ID的词频存储在Redis的哈希表中。博主希望能得到关于提高构建倒排索引速度的建议。
摘要由CSDN通过智能技术生成

问题描述

我想python实现一个简单的搜索引擎,需要建立倒排索引。但我的方法太耗时了(如图),这个算法应该怎么改比较好?

我的思路是,爬虫获取的网页数据保存在MySQL中,然后从数据库获取到数据后进行分词,暂存在字典中(倒排索引),然后保存至redis数据库,索引中保存的是每个单词对应的网页ID和词频。

相关代码

mydb = mysql.connector.connect(

host="localhost",

user="root",

passwd="121314",

database="spider"

)

mycursor = mydb.cursor()

mycursor.execute("SELECT id, data FROM page")

result = mycursor.fetchall()

for row in result:

lexicon(row[0], row[1])

word_dict = {}

r = redis.Redis(host="127.0.0.1", port=6379, db=0)

def lexicon(id, data):

print("Lexiconing and building index.")

word_list = jieba.cut_for_search(str(data))

# 标点符号和停用词

with open('stop_words.txt') as f:

stop_words = [line.strip() for line in f.readlines()]

for item in word_list:

if item not in stop_words:

if item not in word_dict:

word_dict[item] = {}

word_dict[item][id] = 1

r.hset(item, id, 1) # 设置词频至redis中

else:

if idd not in word_dict[item]:

word_dict[item][id] = 1

r.hset(item, id, 1) # 设置词频至redis中

else:

word_dict[item][id] += 1

r.hincrby(item, id, 1) # redis词频+1

网上这方面的资料太少了,最近比较感兴趣,希望有人能给点建议。

建立一个简单的倒排索引表,可以按照以下步骤进行: 1. 读取文本文件,将每个文档中的单词分解成一个个的词项。 2. 对每个词项建立一个包含该词项的文档列表。 3. 对文档列表进行排序,可以按照文档编号或者其他排序方式进行排序。 4. 建立一个词项与文档列表的映射关系表。 以下是一个示例代码: ``` import os # 读取文本文件,将每个文档中的单词分解成一个个的词项 def get_words(file_path): with open(file_path, 'r') as f: return f.read().split() # 对每个词项建立一个包含该词项的文档列表 def build_index(file_dir): index = {} for file_name in os.listdir(file_dir): file_path = os.path.join(file_dir, file_name) words = set(get_words(file_path)) for word in words: if word not in index: index[word] = [] index[word].append(file_name) return index # 对文档列表进行排序 def sort_index(index): for word in index: index[word].sort() # 建立一个词项与文档列表的映射关系表 def build_mapping(index): mapping = {} for word in index: mapping[word] = ','.join(index[word]) return mapping # 示例 file_dir = './documents' index = build_index(file_dir) sort_index(index) mapping = build_mapping(index) print(mapping) ``` 在上面的示例代码中,`file_dir` 是包含文本文件的文件夹,`build_index` 函数会对每个文本文件建立倒排索引表,`sort_index` 函数会对文档列表进行排序,`build_mapping` 函数会建立一个词项与文档列表的映射关系表。最后,我们可以打印出这个映射关系表,得到每个词项对应的文档列表。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值