[英](java) - Storing each word from an input file in an array of Strings
编写方法来完成此操作遇到麻烦,虽然具有该方法的基本概述,但仅需要一些指针/帮助即可完成此操作。
public static String [] readFileAndReturnWords(String filename){
//create array
//read one word at a time from file and store in array
//return the array
}
这是我到目前为止的内容:
public static String readFileAndReturnWords(String filename){
String[] temp = new String[];
//connects file
File file = new File(filename);
Scanner inputFile = null;
try{
inputFile = new Scanner(file);
}
//When arg is mistyped
catch(FileNotFoundException Exception1) {
System.out.println("File not found!");
System.exit(0);
}
//Loops through a file
if (inputFile != null) {
try { //I draw a blank here
我知道一些.next和.hasNext调用是按顺序进行的,我只是不确定如何在问题的上下文中使用这些特定方法。
拆分成单个单词实际上比最初看起来要复杂一些-您拆分了什么?
如果在空格上分开,则句号,逗号和其他标点符号将最终附加到一个单词上,因此
快,懒狗。
将分为:
可能是您想要的,也可能不是。 如果您对非单词字符进行拆分,那么最终您将对撇号,连字符等进行拆分,因此:
因此,这些解决方案各有其问题。 我建议使用单词边界正则表达式匹配器。 它稍微复杂一些,但是仍然存在问题-尝试不同的方法,看看是什么产生了所需的输出。
我提出的解决方案使用Java 8:
public static String[] readFileAndReturnWords(String filename) throws IOException {
final Path path = Paths.get(filename);
final Pattern pattern = Pattern.compile("\\b");
try (final Stream<String> lines = Files.lines(path)) {
return lines.flatMap(pattern::splitAsStream).toArray(String[]::new);
}
}
因此,首先将String
转换为Path
,即文件位置的Java NIO表示形式。 然后,您创建您的Pattern
,这决定了如何分解单词。
您如何简单地使用Files.lines
来流传输文件中的所有行,然后使用Pattern.splitAsStream
将每一行变成单词。 我们使用flatMap
来“平整”流,即每行将是Stream<String>
并且我们已经有了Stream<String>
因此最终得到Stream<Stream<String>>
。 flatMap
被设计为采用Stream<Stream<T>>
并返回Stream<T>
。
将其存储在ArrayList中,因为您不知道文件中存储了多少个单词。
public class Test
{
static ArrayList<String> words;
public static void main(String[] args) throws FileNotFoundException
{
Scanner s = new Scanner(new File("Blah.txt"));
words = new ArrayList<String>();
while(s.hasNext ())
{
String token = s.next ();
if(isAWord(token))
{
if(token.contains ("."))
{
token = token.replace (".","");
}
if(token.contains (","))
{
token = token.replace (",", "");
}
//and remove other characters like braces and parenthesis
//since the scanner gets tokens like
// here we are, < "are," would be a token
//
words.add(token);
}
}
}
private static boolean isAWord(String token)
{
//check if the token is a word
}
}
它应该工作。
如果您真的想使用数组,则可以通过以下方式将ArrayList转换为简单的Array:
String[] wordArray = words.toArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.