Python之AI功能的实现

发布时间 2023-12-20 23:14:21作者: 罗毅豪

使用Python我们可以调用AI库,实现一些AI功能。

1.文本相似度:

import difflib

s1 = "abc"
s2 = "abce"
ratio = difflib.SequenceMatcher(None, s1, s2).quick_ratio()
print(ratio)

2.情感分析:

单句子情感分析

from snownlp import SnowNLP

s = "你人真好"
nlp = SnowNLP(s)
print(nlp.sentiments)
print(nlp.pinyin)

多句子情感分析

from snownlp import SnowNLP

str = "这本书真好看,这本书真是太棒了。这书难看死了"
res_dict = {}
sentences = SnowNLP(str).sentences
for sentence in sentences:
    res_dict[sentence] = SnowNLP(sentence).sentiments
print(res_dict)

3.识别验证码:

import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import ddddocr
from selenium.webdriver.common.by import By

s = Service("chromedriver.exe")
browser = webdriver.Chrome(service=s)
browser.get("https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx")

email = browser.find_element(By.ID,"email")
pwd = browser.find_element(By.ID,"pwd")
code = browser.find_element(By.ID,"code")
imgCode = browser.find_element(By.ID,"imgCode")
loginBtn = browser.find_element(By.ID,"denglu")

email.send_keys("lyh@foxmail.com")
pwd.send_keys("c123456")

ocr = ddddocr.DdddOcr()
img = imgCode.screenshot("myCode.png")
with open("myCode.png", "rb") as fp:
    img = fp.read()
code.send_keys(ocr.classification(img))

loginBtn.click()

time.sleep(10)

要求Python版本为3.9.13,ddddocr版本为1.4.3,Pillow版本为9.5.0

代码部分功能解析:

1.rb是只读二进制文件的意思。

2.fp是file pointer(文件指针)的意思。