读诗小程序的开发

vue版本

JavaScript读取本地文件(采用get请求获取静态资源文件)

vue项目打包成apk项目的静态资源访问路径出现不同(不能有static前的 / ,有的话会找不到资源)

import { ElMessage } from 'element-plus';

export function message(msg, type) {
    ElMessage({
        message: msg,
        showClose: true,
        type: type,
        center: true
    })
}

export const getData = (filePath) => {
    const text = readFile(filePath);
    // const text = readFile("static/poem.txt");
    const textList = text.split("\n");
    const poemList = [];

    for (var i = 0; i < textList.length; i++) {
        const poem = {
            title: "",
            author: "",
            topHalfPart: "",
            halfBottom: "",
            translation: "",
        };

        const splits = textList[i].split("\t");
        poem.translation = "";
        if (splits.length > 1) {
            poem.translation = splits[1];
        }
        const titleString = splits[0];
        const indexOfTitle = titleString.indexOf(" ");
        poem.title = "";
        if (indexOfTitle > 0) {
            poem.title = titleString.substring(0, indexOfTitle);
        }

        const indexOfAuthor = titleString.indexOf(" ", indexOfTitle + 1);
        const indexOfAuthorDynasty = titleString.indexOf(" ", indexOfAuthor + 1);
        poem.author = "";
        if (indexOfAuthorDynasty > indexOfTitle + 1) {
            poem.author = titleString.substring(indexOfTitle + 1, indexOfAuthorDynasty);
        }
        const indexOfTopHalfPart = titleString.indexOf(" ", indexOfAuthorDynasty + 1);

        if (indexOfTopHalfPart > indexOfAuthorDynasty + 1) {
            poem.topHalfPart = titleString.substring(indexOfAuthorDynasty + 1, indexOfTopHalfPart);
            poem.halfBottom = titleString.substring(indexOfTopHalfPart + 1);
        } else {
            const content = titleString.substring(indexOfAuthorDynasty + 1);
            var index = content.indexOf("。", content.length / 2);
            if (index == -1) {
                index = content.indexOf("。", content.length / 3);
                if (index == -1) {
                    index = content.indexOf("。", content.length / 5);
                }
            }
            poem.topHalfPart = content.substring(0, index);
            poem.halfBottom = content.substring(index + 1);
        }

        poemList.push(poem);
    }

    return poemList;
}

function readFile(filePath) {
    let xhr = null;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    const okStatus = document.location.protocol === "file" ? 0 : 200;
    xhr.open("GET", filePath, false);
    xhr.overrideMimeType("text/html;charset=utf-8");
    xhr.send(null);
    return xhr.status === okStatus ? xhr.responseText : null;
}
<template>
    <el-input placeholder="请输入题目查询" class="search-title" v-model="data.searchTitleInput" @input="searchByTitle" />
    <el-input placeholder="请输入作者查询" class="search-author" v-model="data.searchAuthorInput" @input="searchByAuthor" />

    <el-card shadow="hover" v-for="(item, index) in data.showPoemList" :key="index" @click="toPoem(item)"
        style="margin-bottom: 4px; cursor: pointer;">
        <span class="title">{{ item.title }}</span>
        <span>{{ item.author }}</span>
    </el-card>
</template>

<script>
import { getData } from "@/util";
import { onBeforeMount, reactive } from "vue";
import { useRouter } from 'vue-router';

export default {
    name: "Home",
    setup() {
        const data = reactive({
            poemList: [],
            showPoemList: [],
            searchTitleInput: "",
            searchAuthorInput: "",
        });

        function searchByTitle() {
            data.showPoemList = data.poemList.filter(poem => poem.title.indexOf(data.searchTitleInput.trim()) > -1);
        }
        function searchByAuthor() {
            data.showPoemList = data.poemList.filter(poem => poem.author.indexOf(data.searchAuthorInput.trim()) > -1);
        }

        onBeforeMount(() => {
            data.poemList = getData("static/poem.txt");
            data.showPoemList = data.poemList;
        });

        const myRouter = useRouter();
        function toPoem(item) {
            myRouter.push({
                path: "/poem",
                query: {
                    title: item.title,
                    author: item.author,
                    topHalfPart: item.topHalfPart,
                    halfBottom: item.halfBottom,
                    translation: item.translation
                }
            });
        }

        return {
            data,
            searchByTitle,
            searchByAuthor,
            toPoem,
        };
    },
};
</script>

<style scoped>
.search-title {
    margin-top: 4vh;
    margin-bottom: 1vh;
    margin-left: 5vw;
    width: 90vw;
}
.search-author {
    margin-top: 1vh;
    margin-left: 5vw;
    width: 90vw;
    margin-bottom: 2vh;
}

.title {
    margin: 0 10px;
    color: crimson;
    font-size: 20px;
}
</style>

vue系统展示
在这里插入图片描述

Java版本的系统

采用Swing编写

主窗体

package poem;

import javax.swing.*;
import java.awt.*;
import java.io.FileNotFoundException;
import java.util.ArrayList;

/**
 * @author bbyh
 * @date 2023/3/7 0007 13:27
 * @description
 */
public class MainFrame extends JFrame {
    private static final ArrayList<Poem> RES = new ArrayList<>(8);

    public MainFrame() {
        this.setTitle("阅读古诗");
        this.setSize(1200, 800);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setLayout(null);

        Font font = new Font("宋体", Font.BOLD, 20);

        JTextField searchInput = new JTextField();
        JButton searchByTitle = new JButton("按题目搜索");
        JButton searchByAuthor = new JButton("按作者搜索");
        JButton display = new JButton("显示内容");

        searchInput.setFont(font);
        searchByTitle.setFont(font);
        searchByAuthor.setFont(font);
        display.setFont(font);

        this.add(searchInput);
        this.add(searchByTitle);
        this.add(searchByAuthor);
        this.add(display);

        searchInput.setBounds(150, 50, 300, 40);
        searchByTitle.setBounds(460, 50, 200, 40);
        searchByAuthor.setBounds(670, 50, 200, 40);
        display.setBounds(890, 50, 150, 40);

        JLabel titleDisplay = new JLabel("", JLabel.CENTER);
        JLabel authorDisplay = new JLabel("", JLabel.CENTER);
        JLabel contentDisplay = new JLabel("", JLabel.CENTER);
        JLabel translateDisplay = new JLabel("", JLabel.CENTER);

        titleDisplay.setFont(font);
        authorDisplay.setFont(font);
        contentDisplay.setFont(font);
        translateDisplay.setFont(font);

        this.add(titleDisplay);
        this.add(authorDisplay);
        this.add(contentDisplay);
        this.add(translateDisplay);

        titleDisplay.setBounds(400, 150, 400, 50);
        authorDisplay.setBounds(700, 210, 400, 50);
        contentDisplay.setBounds(300, 270, 600, 120);
        translateDisplay.setBounds(200, 400, 800, 200);

        JLabel searchResultDisplay = new JLabel("", JLabel.CENTER);
        searchResultDisplay.setFont(font);

        searchByTitle.addActionListener(e -> {
            String inputText = searchInput.getText();
            if (inputText.trim().length() == 0) {
                searchResultDisplay.setText("请输入题目后搜索");
                JOptionPane.showMessageDialog(null, searchResultDisplay);
                return;
            }

            RES.clear();
            for (Poem poem : Read.POEM_LIST) {
                if (poem.title.contains(inputText)) {
                    RES.add(poem);
                }
            }

            ArrayList<String> res = new ArrayList<>();
            for (int i = 0; i < RES.size(); i++) {
                res.add(i + ": " + RES.get(i).title);
            }
            new SearchTip(changeHtml(res.toArray(new String[0])));
        });
        searchByAuthor.addActionListener(e -> {
            String inputText = searchInput.getText();
            if (inputText.trim().length() == 0) {
                searchResultDisplay.setText("请输入作者后搜索");
                JOptionPane.showMessageDialog(null, searchResultDisplay);
                return;
            }

            RES.clear();
            for (Poem poem : Read.POEM_LIST) {
                if (poem.author.contains(inputText)) {
                    RES.add(poem);
                }
            }

            ArrayList<String> res = new ArrayList<>();
            for (int i = 0; i < RES.size(); i++) {
                res.add(i + ": " + RES.get(i).author + " " + RES.get(i).title);
            }
            new SearchTip(changeHtml(res.toArray(new String[0])));
        });
        display.addActionListener(e -> {
            String inputText = searchInput.getText();
            if (inputText.trim().length() == 0) {
                searchResultDisplay.setText("请选择第几首后显示");
                JOptionPane.showMessageDialog(null, searchResultDisplay);
                return;
            }

            Poem poem = RES.get(Integer.parseInt(inputText));
            generateResult(poem, titleDisplay, authorDisplay, contentDisplay, translateDisplay);
        });
    }

    public static void main(String[] args) {
        try {
            Read.cache("");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

        new MainFrame().setVisible(true);
    }

    private static String changeHtml(String[] msg) {
        StringBuilder builder = new StringBuilder();
        builder.append("<html><body><p>");
        for (String s : msg) {
            builder.append(s).append("<br/>").append("<br/>");
        }
        builder.append("</p></body></html>");
        return builder.toString();
    }

    private static void generateResult(Poem poem, JLabel titleDisplay, JLabel authorDisplay, JLabel contentDisplay, JLabel translateDisplay) {
        titleDisplay.setText(changeHtml(new String[]{poem.title}));
        authorDisplay.setText(changeHtml(new String[]{poem.author}));
        contentDisplay.setText(changeHtml(new String[]{poem.topHalfPart, poem.halfBottom}));
        translateDisplay.setText(changeHtml(new String[]{poem.translation}));
    }
}

文件读取工具类

package poem;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Scanner;

/**
 * @author bbyh
 * @date 2023/2/27 0027 9:15
 * @description
 */
public class Read {
    private static final ArrayList<String> POEM_STR = new ArrayList<>(136);
    public static final ArrayList<Poem> POEM_LIST = new ArrayList<>(136);
    private static final String DEFAULT_PATH = "poem.txt";
    private static final String PREFIX = System.getProperty("user.dir");

    public static void cache(String filePath) throws FileNotFoundException {
        File file;
        if (Objects.equals(filePath, "")) {
            file = new File(PREFIX + System.getProperty("file.separator") + DEFAULT_PATH);
        } else {
            file = new File(PREFIX + System.getProperty("file.separator") + filePath);
        }

        if (!file.exists()) {
            throw new FileNotFoundException("文件未找到");
        }

        Scanner scanner;
        try {
            scanner = new Scanner(Files.newInputStream(file.toPath()), String.valueOf(StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        while (scanner.hasNextLine()) {
            String nextLine = scanner.nextLine();
            if (Objects.equals(nextLine, "")) {
                continue;
            }
            POEM_STR.add(nextLine);
        }

        generatePoemList();
    }

    private static void generatePoemList() {
        for (String str : POEM_STR) {
            String[] split = str.split("\t");

            String titleString = split[0];
            String translation = "";
            if (split.length > 1) {
                translation = split[1];
            }
            try {
                int indexOfTitle = titleString.indexOf(" ");
                String title = "";
                if (indexOfTitle > 0) {
                    title = titleString.substring(0, indexOfTitle);
                }

                int indexOfAuthor = titleString.indexOf(" ", indexOfTitle + 1);
                int indexOfAuthorDynasty = titleString.indexOf(" ", indexOfAuthor + 1);
                String author = "";
                if (indexOfAuthorDynasty > indexOfTitle + 1) {
                    author = titleString.substring(indexOfTitle + 1, indexOfAuthorDynasty);
                }
                int indexOfTopHalfPart = titleString.indexOf(" ", indexOfAuthorDynasty + 1);

                String topHalfPart;
                String halfBottom;

                if (indexOfTopHalfPart > indexOfAuthorDynasty + 1) {
                    topHalfPart = titleString.substring(indexOfAuthorDynasty + 1, indexOfTopHalfPart);
                    halfBottom = titleString.substring(indexOfTopHalfPart + 1);
                } else {
                    String content = titleString.substring(indexOfAuthorDynasty + 1);
                    int index = content.indexOf("。", content.length() / 2);
                    if (index == -1) {
                        index = content.indexOf("。", content.length() / 3);
                        if (index == -1) {
                            index = content.indexOf("。", content.length() / 5);
                        }
                    }
                    topHalfPart = content.substring(0, index);
                    halfBottom = content.substring(index + 1);
                }

                Poem poem = new Poem();
                poem.title = title;
                poem.author = author;
                poem.topHalfPart = topHalfPart;
                poem.halfBottom = halfBottom;
                poem.translation = translation;
                POEM_LIST.add(poem);
            } catch (Exception e) {
                System.out.println(titleString);
                System.out.println(translation);
            }
        }
    }

    private static void judge() {
        for (Poem poem : POEM_LIST) {
            if (Objects.equals(poem.title, "") || Objects.equals(poem.author, "") || Objects.equals(poem.halfBottom, "")
                    || Objects.equals(poem.topHalfPart, "") || Objects.equals(poem.translation, "")) {
                System.out.println(poem);
            }
        }
    }
}

Java版本演示结果
在这里插入图片描述
在这里插入图片描述

爬取数据 BeautifulSoup 的使用

import requests
from bs4 import BeautifulSoup

url = 'https://so.gushiwen.cn/gushi/xiaoxue.aspx'
strHtml = requests.get(url)
html = strHtml.text

bs = BeautifulSoup(html, "html.parser")
body = bs.body
data = body.find_all('div', {'class': 'sons'})

href_list = []

for d in data:
    plist = d.find_all('div')
    for p in plist:
        spanList = p.find_all('span')
        for span in spanList:
            a = span.find('a')['href']
            href_list.append(a)

contentList = []
translateList = []

for href in href_list:
    url = href
    strHtml = requests.get(url)
    html = strHtml.text

    bs = BeautifulSoup(html, "html.parser")
    body = bs.body
    data = body.find_all('div', {'class': 'cont'})
    contentList.append(data[1].get_text(separator=" ", strip=True))

    tempStr = ""
    data = body.find_all('div', {'class': 'contyishang'})
    for d in data:
        plist = d.find_all('p')
        for p in plist:
            tempStr += p.get_text(separator=" ", strip=True)
            break
        break
    translateList.append(tempStr)

with open("poem.txt", "w", encoding='utf-8') as f:
    for i in range(len(contentList)):
        f.write(contentList[i] + "\t" + translateList[i] + "\n")

print("写入完毕")

转换为手机APP

采用HBuilder的5+App进行转换,可以将vue的应用打包变为apk,安装在安卓手机上使用

项目下载

Java版本
链接:https://pan.baidu.com/s/1-EZTUkD1X9h-VqPixSqnPw
提取码:0925

vue版本
链接:https://pan.baidu.com/s/1EvxGHw0VTnCDMEv5FojVng
提取码:0925

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值