You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将文本文件中的每个单词转为独立对象并输出到控制台

Python 实现

先定义一个用来封装单词的简单类,你可以根据需求扩展它的属性(比如词性、释义等):

class Word:
    def __init__(self, text):
        self.text = text

    def __repr__(self):
        # 自定义对象的控制台输出格式,方便查看内容
        return f"Word(text='{self.text}')"

接着编写读取文件、生成对象并输出的逻辑:

word_objects = []
try:
    # 以UTF-8编码打开文件,自动处理关闭操作
    with open('Dictionary.txt', 'r', encoding='utf-8') as file:
        for line in file:
            word = line.strip()
            if word:  # 跳过空行,避免生成无效对象
                word_objects.append(Word(word))
except FileNotFoundError:
    print("错误:找不到Dictionary.txt文件")

# 把所有对象输出到控制台
for obj in word_objects:
    print(obj)

Java 实现

先定义Word类,封装单词数据:

public class Word {
    private String text;

    public Word(String text) {
        this.text = text;
    }

    @Override
    public String toString() {
        // 自定义对象的字符串表现,控制台输出时更直观
        return "Word{text='" + text + "'}";
    }

    // 按需添加getter/setter方法
    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

再编写主类处理文件读取和对象创建:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DictionaryProcessor {
    public static void main(String[] args) {
        List<Word> wordObjects = new ArrayList<>();
        String filePath = "Dictionary.txt";

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                String word = line.trim();
                if (!word.isEmpty()) {
                    wordObjects.add(new Word(word));
                }
            }
        } catch (IOException e) {
            System.out.println("处理文件时出错:" + e.getMessage());
        }

        // 输出所有对象到控制台
        for (Word wordObj : wordObjects) {
            System.out.println(wordObj);
        }
    }
}

内容的提问来源于stack exchange,提问作者Stef Konstantinou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 01:03:02