STEP 1.2: SENTENCE TOKENIZATION WITH spaCy
查了一些资料之后,我决定将reviews 和 sentences 的对应关系存在postgresql数据库里,方便以后随时检索和调整。我没有用Json文件来存,是因为之前做过一个比较大的项目,用json来存,检索的时候发现速度很慢。在检索速度上,还是关系型数据库的表现最好最稳定了。再加上,我正好手头有另一个项目,之前是用mongoDB来存储和检索的,现在想改成psql,所以顺便拿这个项目练练手。
我要建的对应关系其实很简单,只需要实现下面几个功能就可以了:
- 可以迅速提取和检索我想要的reviews — 因此需要reviewID
- 可以迅速提取和检索我想要的sentences — 因此需要sentenceID可以迅速提取和检索我想要的sentences — 因此需要sentenceID
- 可以迅速在reviews 和 sentences 之间转换,给定review,可以马上提取出它对应的sentences, 反之亦然。可以迅速在reviews 和 sentences 之间转换,给定review,可以马上提取出它对应的sentences, 反之亦然。
在review table 里面,需要有:
- reviewID, SERIAL PRIMARY
- yelp_userID (from Yelp, not NULL)yelp_userID (from Yelp, not NULL)
- yelp_restID (from Yelp, not NULL)yelp_restID (from Yelp, not NULL)
- review_date (can be NULL)review_date (can be NULL)
- text
在sentence table 里面,需要有:
- sentenceID, SERIAL PRIMARY
- begin_position (sentence index) begin_position (sentence index)
- reviewID, FOREIGNreviewID, FOREIGN
- texttext
趁这个机会,学习了一下postgresql的python接口psycopg2
。吐槽一下,这个包的名字取得特别地反直觉,不知道为什么要叫psycopg
,从名字上看不出跟psql有什么关系… 看起来倒是非常像psychopath
…
下面是我用来断句的程序,里面包含了从PSQL提取待处理文本,传入spaCy,再将结果传回PSQL的函数。
import spacy
import time
import sys
import numpy as np
import psycopg2
import logging
import time
def get_500_unsplitted_text():
# get 500 text-to-be-processed at a time from the DB.
select_query = """select review_id, content from reviews where split_flag = false limit 500;"""
cursor.execute(select_query)