gpt4 book ai didi

java - 如何替换每个句子的第一个单词(来自输入文件)

转载 作者:太空宇宙 更新时间:2023-11-04 07:29:26 24 4
gpt4 key购买 nike

我的问题是我有一个输入文件,我必须在没有 4 个单词的输出文件中重写文本(“a”),(“the”),(“A”),(“The”)。我设法解决了“a”和“the”的问题,但没有解决“A”和“The”的问题。你能帮我解决我的代码吗?提前致谢。以下是问题、输入和我的代码:

问题:

英语中,单词“a”和“the”大多可以从句子中删除,而不会影响含义。这是压缩文本文件大小的机会!编写一个程序,逐行输入一个文本文件,然后写出一个新的文本文件,其中每一行都删除了无用的单词。

首先编写一个简单版本的程序,将每行中的子字符串“a ”和“the ”替换为一个空格。这将删除许多单词,但有时这些单词出现在行的开头或结尾,有时这些单词以大写字母开头。因此,改进您的第一个程序,使其也能处理这些情况。

C:>java 删除器 < verbose.txt > terse.txt

注意:String类有多种replace()方法可以简化这个程序。尝试在不使用它们的情况下编写此程序。

输入文件:

小说是描述虚构故事的长篇散文叙事人物和事件,通常以连续故事的形式出现。该流派在中世纪和早期领域有着历史根源现代浪漫主义和中篇小说的传统。

代码:

import java.util.Scanner;
import java.io.*;

class File_Compressor
{
public static void main(String[]args) throws IOException
{
int loc=0;
String line="";

File input=new File ("input.txt");
Scanner scan=new Scanner(input);
File output=new File("Hello2.java");
PrintStream print=new PrintStream(output);

while (scan.hasNext())
{line=scan.nextLine().trim();

while(line.indexOf("A")>0||line.indexOf("The")>0||line.indexOf(" a")>0||line.indexOf(" the ")>0)
{
if (line.indexOf("A")>0)
{loc=line.indexOf("A");
line=line.substring(loc+1);}

else if (line.indexOf("The")>0)
{loc=line.indexOf("The");
line=line.substring(loc+3);
}

else if (line.indexOf(" a ")>0)
{loc=line.indexOf(" a ");
left=line.substring(0,loc+1);
right=line.substring(loc+2);
line=left+right;}

else if (line.indexOf(" the ")>0)
{loc=line.indexOf(" the ");
left=line.substring(0,loc+1);
right=line.substring(loc+4);
line=left+right;}
}
print.println(line);
}
}

}

最佳答案

由于您正在逐行读取文件,因此将每一行分成一个单词数组

line=scan.nextLine().trim();
String[] words = line.split("\\s+");
String sentence = "";
for (int i = 0; i < words.length; i++) {
if(!(words[i].equalsIgnoreCase("a") || words[i].equalsIgnoreCase("the"))){
sentence += words[i] + " ";
}
}
System.out.println(sentence);

关于java - 如何替换每个句子的第一个单词(来自输入文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17971019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com