feiyu02
2024-11-19 752e00503f672ddfe2066afb6c235721a3a912b5
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package cn.flightfeather.supervision.common.nlp
 
import cn.flightfeather.supervision.infrastructure.utils.GsonUtils
import com.aliyuncs.DefaultAcsClient
import com.aliyuncs.alinlp.model.v20200629.GetPosChGeneralRequest
import com.aliyuncs.profile.DefaultProfile
import com.google.gson.JsonParser
import org.springframework.stereotype.Component
 
/**
 * nlp自然语言处理
 */
@Component
class NlpController {
 
    private val client: DefaultAcsClient
 
    companion object {
        const val accessKeyId = "LTAI4FvmhG97saKL33tDqUV8"
        const val accessKeySecret = "3PyluVDS97GTGVmm1p3s6vbLkyqZMf"
 
        private const val TAG = "NlpController"
    }
 
    init {
        val defaultProfile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret)
        client = DefaultAcsClient(defaultProfile)
    }
 
    fun execute(str: String): List<String> {
        val result = mutableListOf<String>()
 
        val request = GetPosChGeneralRequest().apply {
            setSysEndpoint("alinlp.cn-hangzhou.aliyuncs.com")
            serviceCode = "alinlp"
            tokenizerId = "GENERAL_CHN"
            text = str
        }
 
        val start = System.currentTimeMillis()
        val response = client.getAcsResponse(request)
 
        println(response.hashCode())
        println(response.requestId + "\n" + response.data + "\n" + "cost:" + (System.currentTimeMillis() - start))
 
        val json = JsonParser.parseString(response.data).asJsonObject
        if (json["success"].asBoolean) {
            val r = json["result"].toString()
            val list = GsonUtils.parserJsonToArrayBeans(r, NlpWord::class.java)
            list.forEach {
                if (it.pos in listOf("VV", "NR", "NN", "LC", "FW")) {
                    result.add(it.word)
                }
            }
        } else {
            throw IllegalStateException("${TAG}: 词性标注接口请求失败,错误如下,\n$json")
        }
 
        return result
    }
}