阿里云自然语言NLP服务实现文本纠错功能

老规矩,先注册阿里云账号,开通自然语言处理NLP服务,地址如下:

自然语言处理 NLP 控制台,将基础文本服务和高级文本服务都开通。开通后可进入API测试进行测试

觉得效果还不错的可以进行下一步配置了。

1.依赖配置

        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.5.13</version>
        </dependency>

        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-alinlp</artifactId>
            <version>1.8.17</version>
            <exclusions>
                <exclusion>
                    <groupId>com.aliyun</groupId>
                    <artifactId>aliyun-java-sdk-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

2.controller层

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.alinlp.model.v20200629.GetEcChGeneralRequest;
import com.aliyuncs.alinlp.model.v20200629.GetEcChGeneralResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.lxy.other.utils.TextCorrectRequest;
import com.lxy.other.utils.TextCorrectResponse;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TextCorrect {
    private String accessKeyId="阿里云账号AccessKeyId";

    private String accessKeySecret="阿里云账号AccessKeySecret";

    private IAcsClient createAcsClient() {
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou",
                accessKeyId,
                accessKeySecret
        );
        return new DefaultAcsClient(profile);
    }

    @PostMapping("/api/text/correct")
    public TextCorrectResponse correctText(@RequestBody TextCorrectRequest request) {
        IAcsClient client = createAcsClient();
        GetEcChGeneralRequest aliRequest = new GetEcChGeneralRequest();
        aliRequest.setSysEndpoint("alinlp.cn-hangzhou.aliyuncs.com");
        aliRequest.setServiceCode("alinlp");
        aliRequest.setText(request.getText()); // 从请求体获取待纠错文本

        try {
            GetEcChGeneralResponse response = client.getAcsResponse(aliRequest);
            JSONObject jsonData = JSON.parseObject(response.getData());
            System.out.println("完整响应数据:\n" + JSON.toJSONString(jsonData, true));
                JSONObject result = jsonData.getJSONObject("result");
            // 构建标准化响应
            return TextCorrectResponse.builder()
                    .success(true)
                    .sourceText(request.getText())
                    .targetText(result.getString("target"))
                    .edits(result.getJSONArray("edits"))
                    .build();

        } catch (ClientException | com.aliyuncs.exceptions.ClientException e) {
            return TextCorrectResponse.builder()
                    .success(false)
                    .errorMessage(e.getMessage())
                    .build();
        }
    }
}

3.实体层

TextCorrectRequest

@Getter
@Setter
@Component
public class TextCorrectRequest {
    private String text;
}

 TextCorrectResponse

@Getter
@Setter
@Builder
public class TextCorrectResponse {
    private boolean success;
    private String sourceText;
    private String targetText;
    private JSONArray edits;
    private boolean hasError;
    private String errorCode;
    private String errorMessage;
}

测试页面:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>阿里云文本纠错测试(Vue版)</title>
    <style>
        .container { max-width: 800px; margin: 50px auto; }
        .highlight { background-color: #ffd70080; }
        .diff-remove { color: #dc3545; text-decoration: line-through; }
        .diff-add { color: #28a745; }
    </style>
</head>
<body>
<div id="app">
    <div class="container">
        <h2 class="mb-4">文本纠错测试工具</h2>
        <!-- 输入区域 -->
        <div class="mb-3">
            <label class="form-label">输入待纠错文本:</label>
            <textarea
                    v-model="inputText"
                    class="form-control"
                    rows="4"
                    placeholder="示例:中国只造行业高速发展,随这经济持续高速发站"
            ></textarea>
        </div>

        <button
                class="btn btn-primary mb-3"
                @click="submitText"
                :disabled="isLoading"
        >
            <span v-if="!isLoading">开始纠错</span>
            <span v-else>
                处理中...
            </span>

        </button>

        <!-- 错误提示 -->
        <div v-if="error" class="alert alert-danger">
            {{ error }}
        </div>

        <!-- 结果展示 -->
        <div v-if="result" class="card">
            <div class="card-header">纠错结果</div>
            <div class="card-body">
                <!-- 对比展示 -->
                <div class="mb-3">
                    <h5>文本对比:</h5>
                    <div class="text-muted" ></div>
                </div>

                <!-- 修改详情 -->
                <div>
                    <h5>修改详情:</h5>
                    <ul class="list-group">
                        <li
                                v-for="(edit, index) in result.edits"
                                :key="index"
                                class="list-group-item"
                        >
                            位置 {{ edit.pos + 1 }}:
                            <span class="diff-remove">{{ edit.src }}</span> →
                            <span class="diff-add">{{ edit.tgt }}</span>
                        </li>
                    </ul>
                    <button @click="swap">点击替换</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            inputText: '',
            result: [],
            isLoading: false,
            error: null
        },
        methods: {
            async submitText() {
                if (!this.inputText.trim()) {
                    this.error = '请输入需要纠错的文本';
                    return;
                }

                this.isLoading = true;
                this.error = null;
                this.result = null;

                try {
                    const response = await axios.post(
                        '/api/text/correct',
                        { text: this.inputText }
                    );

                    if (response.data.success) {
                        this.result = {
                            sourceText: response.data.sourceText,
                            targetText: response.data.targetText,
                            edits: response.data.edits
                        };
                    } else {
                        this.error = `错误:${response.data.errorMessage || '未知错误'}`;
                    }
                } catch (err) {
                    this.error = `请求失败:${err.message}`;
                } finally {
                    this.isLoading = false;
                }
            },
            swap(){
                this.inputText = this.result.targetText;
            }
        }
    });
</script>
</body>
</html>

阿里云自然语言处理的文本纠错服务不是很强大,但对比百度和腾讯云的纠错服务还是能行的,不太满意的小伙伴可以找其他替代品。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值