我的问题是我有一个输入文件,我必须在没有 4 个单词的输出文件中重写文本(“a”),(“the”),(“A”),(“The”)。我设法解决“a”和“the”,但不能解决“A”和“The”。你能帮我写代码吗?提前致谢。下面是问题,输入和我的代码:
问题:
英语中的“a”和“the”大部分都可以从句子中去掉而不影响意思。这是压缩文本文件大小的机会!编写一个程序,逐行输入一个文本文件,然后写出一个新的文本文件,其中每一行都删除了无用的单词。
首先编写一个简单版本的程序,将每行中的子字符串“a”和“the”替换为一个空格。这将删除许多单词,但有时这些单词出现在行首或行尾,有时单词以大写字母开头。因此,请改进您的第一个程序,以便它也能处理这些情况。
C:>java Remover <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);
}
}
}