核心步骤:

  • 创建数据库连接
def get_conn():
"""
获取连接和游标
:return:
"""
conn=pymysql.connect(host="127.0.0.1",
user="root",
password="000000",
db="news",
charset="utf8")
cursor=conn.cursor()
return conn,cursor

def close_conn(conn, cursor):
"""
关闭连接和游标
:param conn:
:param cursor:
:return:
"""
if cursor:
cursor.close()
if conn:
conn.close()
  • 读取文件
fn = open('F:\\PyCharm\\newsProject\\file\\youxi.txt', 'rt', encoding='utf-8')  # 打开文件
string_data = fn.read() # 读出整个文件
fn.close() # 关闭文件
  • 文本预处理
pattern = re.compile(u'\t|\n|\.|-|:|;|\)|\(|\?|"')  # 定义正则表达式匹配模式
string_data = re.sub(pattern, '', string_data) # 将符合模式的字符去除
  • 文本分词
seg_list_exact = jieba.cut(string_data, cut_all=False)  # 精确模式分词
  • 去除停用词(停用词文件:stopword.txt)
remove_words = set()
fr = open('F:\\PyCharm\\newsProject\\stopword\\stopword.txt', encoding = 'UTF-8')
for word in fr:
remove_words.add(str(word).strip())
fr.close()
for word in seg_list_exact:  # 循环读出每个分词
if word not in remove_words: # 如果不在去除词库中
object_list.append(word) # 分词追加到列表
  • 词频统计并导入数据库
word_counts = collections.Counter(object_list)  # 对分词做词频统计
word_counts_top10 = word_counts.most_common(100) # 获取前10最高频的词
print(word_counts_top10) # 输出检查
conn,course= get_conn()
for i in word_counts_top10:
sql="insert into result_game (name,values_data) values(%s,%s)"
course.execute(sql,i)
conn.commit()
close_conn(conn,course)