当前位置:Gxlcms > 数据库问题 > Python 连接MongoDB并比较两个字符串相似度的简单示例

Python 连接MongoDB并比较两个字符串相似度的简单示例

时间:2021-07-01 10:21:17 帮助过:29人阅读

一,Python连接MongoDB

大致步骤:创建MongoClient---> 获取 DataBase --->获取Collection,代码如下:

client = MongoClient(host="127.0.0.1", port=10001)
db = client[database_name]
db.authenticate(name="user_name", password="password")
coll = db.get_collection("collection_name")

 

二,Python MongoDB 查询

以uid为条件进行查询。由于 collection_name 中定义了多个字段,这里只想返回 chat 字段的内容,并且不返回 _id 字段内容。故查询条件如下:

coll.find({"uid": 123456789}, {"_id": 0, "chat": 1})

 

MongoDB查询返回的每一条记录都是一个 dict:{"chat":"这是一条发言内容"},再将之转化成 chats列表(list) 存储每一条发言内容:

 list_chat = list(coll.find({"uid": 123456789}, {"_id": 0, "chat": 1}))
 chats = [d[chat] for d in list_chat]

 

三,Python比较两个字符串的相似度

给定一个列表(list),列表中的每个元素都是一个字符串,计算列表中相邻两个元素的相似度。

#查找chats 列表 里面 相邻 字符串 之间的 相似度
def compute_similar():
    chats = uid_chats()
    for index in range(len(chats) - 1):
        ratios = similar_ratio(chats[index], chats[index+1])
        print(ratios)

具体的字符串相似度计算,由SequenceMatcher实现,它忽略了字符串中存在空格的情况。

#lambda 表达式表示忽略 “  ”(空格),空格不参与相似度地计算
SequenceMatcher(lambda x:x==" ", strA, strB).ratio()

 

四,完整代码

系统环境 pycharm2016.3  Anaconda3 Python3.6

from pymongo import MongoClient
from difflib import SequenceMatcher

client = MongoClient(host="127.0.0.1", port=10001)
db = client[database_name]
db.authenticate(name="user_name", password="password")

coll = db.get_collection("collection_name")

def uid_chats():
    list_chat = list(coll.find({"uid": 123456789}, {"_id": 0, "chat": 1}))
    chats = [d[chat] for d in list_chat]
    print(chats)
    return chats


def similar_ratio(strA, strB):
    return SequenceMatcher(lambda x:x==" ", strA, strB).ratio()

#查找list里面相邻字符串之间的相似度
def compute_similar():
    chats = uid_chats()
    for index in range(len(chats) - 1):
        ratios = similar_ratio(chats[index], chats[index+1])
        print(ratios)


if __name__ == "__main__":
    compute_similar()

 

原文:http://www.cnblogs.com/hapjin/p/7895027.html

Python 连接MongoDB并比较两个字符串相似度的简单示例

标签:记录   htm   系统   get   index   sof   连接   chat   ati   

人气教程排行