Python代码

1
2
3
4
5
6
7
8
9
10
11
import fastText
import jieba

# 判断小说类型的调用语句
def judge(novel):
print(novel, " : ", classifier.predict(" ".join(jieba.cut(novel))))
return str(classifier.predict(" ".join(jieba.cut(novel)))[0][0])

# classifier = fastText.train_supervised("data/novel_names.txt", lr=0.1, wordNgrams=1, loss="hs", epoch=20)
# model = classifier.save_model("data/novel_names.model")
classifier = fastText.load_model("data/novel_names.model")

C++代码(Qt为例)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <QCoreApplication>
#include <iostream>
#include <Python.h>
#include <QDebug>
using namespace std;

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

Py_Initialize();

if (!Py_IsInitialized())
{
return -1;
}

PyObject* pModule = PyImport_ImportModule("wtnn"); // 模块名(不带后缀的文件名)
if (!pModule)
{
printf("Can't open python file!\n");
return -1;
}

PyObject* pFun = PyObject_GetAttrString(pModule, "judge"); // 函数名

if (!pFun)
{
printf("Get function failed");
return -1;
}

PyObject* args = Py_BuildValue("(s)", "测试"); // 构建参数,为元组形式
PyObject* result = PyObject_CallObject(pFun, args);
if (result)
{
char* str = nullptr;
PyArg_Parse(result, "s", &str);
qDebug() << str; // 可以直接printf,但是中文乱码,得用qDebug
}

Py_Finalize();

return a.exec();
}

pro文件

1
2
INCLUDEPATH += -I C:\Users\HP\AppData\Local\Programs\Python\Python36\include
LIBS += -LC:\Users\HP\AppData\Local\Programs\Python\Python36\libs -lpython36