解析txt文件并搜索特定单词

发布于 2024-12-12 00:58:51 字数 529 浏览 0 评论 0原文

我有以下文本文件,我想知道如何解析它并搜索 Cell 和 Engine 单词,我想要的是打印出包含 Cell、Engine 单词的方法名称。以下是 txt 文件,不要将其视为 java 代码,因为我已经将其移动到 txt 文件以进行解析。

@Test
  public void testGetMonsters() {
        Cell cell11 = aBoard.getCell(1, 1);
        theEngine = new Engine(theGame);   
  }

  @Test
  public void testDxDyPossibleMove() {
        Cell cell11 = aBoard.getCell(1, 1);
  }   

所需的解析输出如下所示:

testGetMonsters class contains Cell and Engine words
testDxDyPossibleMove class contains Cell word

I have the following text fil, I'm wondering how can I parse it and search for Cell And Engine words, what I want is to print out the method name that contains Cell, Engine words. the following is the txt file don't look at it as java code since I already moved it to txt file for parsing purposes.

@Test
  public void testGetMonsters() {
        Cell cell11 = aBoard.getCell(1, 1);
        theEngine = new Engine(theGame);   
  }

  @Test
  public void testDxDyPossibleMove() {
        Cell cell11 = aBoard.getCell(1, 1);
  }   

The desired output of parsing looks like:

testGetMonsters class contains Cell and Engine words
testDxDyPossibleMove class contains Cell word

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

柳絮泡泡 2024-12-19 00:58:51

您可能想要使用正则表达式和 Java 的模式匹配工具。请查看正则表达式和 Java 编程语言以获取示例用法。

简单的例子:

Pattern cellPattern = Pattern.compile("Cell");
    while (fileReader.ready()) {
        String inputLine = fileReader.readLine();
        Matcher cellMatcher = cellPattern.matcher(inputLine);
        if(cellMatcher.lookingAt()) {
            //This line contains the word "Cell"

确定您是否/属于哪个班级是另一个问题......您需要一个“词法分析器”。 JavaCC 是一个很好的起点。

You probably want to use regular expressions and the pattern matching facility of Java. Take a look at Regular Expressions and the Java Programming Language for example usage.

Quick example:

Pattern cellPattern = Pattern.compile("Cell");
    while (fileReader.ready()) {
        String inputLine = fileReader.readLine();
        Matcher cellMatcher = cellPattern.matcher(inputLine);
        if(cellMatcher.lookingAt()) {
            //This line contains the word "Cell"

Determining if / what class you're in is another question... you'll need a "lexer" for that. JavaCC is a good starting point there.

孤独岁月 2024-12-19 00:58:51

我没有看到您的代码和问题之间的链接,但是:

String text = new Scanner(yourFile).useDelimiter("\\Z").next();
String wordsToLookFor = Arrays.asList("cell", "engine");

List<String> wordsContained = new ArrayList<String>();

for(String word : wordsToLookFor){
  if(text.contains(word)) {
     wordsContained.add(word);
  }
}

System.out.println(yourFile.getName() + " contains " + wordsContained);

I don't see the link between your code and your question but :

String text = new Scanner(yourFile).useDelimiter("\\Z").next();
String wordsToLookFor = Arrays.asList("cell", "engine");

List<String> wordsContained = new ArrayList<String>();

for(String word : wordsToLookFor){
  if(text.contains(word)) {
     wordsContained.add(word);
  }
}

System.out.println(yourFile.getName() + " contains " + wordsContained);
尬尬 2024-12-19 00:58:51

哒哒哒!

package textsearch;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TextSearch {

    public static void main(final String[] args) throws Exception {

        final URL testFileURL = Thread.currentThread().getContextClassLoader().getResource("textsearch/test.txt");
        final File input = new File(testFileURL.toURI());
        final FileReader reader = new FileReader(input);

        final SearchString search1 = new SearchString("Cell");
        final SearchString search2 = new SearchString("Engine");

        final List<SearchString> searches = new ArrayList<SearchString>();
        searches.add(search1);
        searches.add(search2);

        final Search search = new Search(searches);

        try {
            search.search(reader);
        } finally {
            reader.close();
        }

        if(search.hasPositives()) {
            System.out.print("File " + input.getName() + " contains the words ");
            search.printPositives();
            System.out.println("");
        } else {
            System.out.println("File " + input.getName() + " didn't contain any of the search terms.");
        }

    }

    private static class SearchString {

        final String searchString;
        final ParsePosition pos;

        SearchString(final String searchString) {

            if(searchString == null || searchString.isEmpty())
                throw new IllegalArgumentException("I can't search for nothing!");

            this.searchString = searchString;
            pos = new ParsePosition(0);

        }

        boolean checkNextChar(final char c) {

            if(searchString.charAt(pos.getIndex()) == c) {
                pos.setIndex(pos.getIndex() + 1);
                if(pos.getIndex() >= searchString.length()) {
                    pos.setIndex(0);
                    return true;
                }
                return false;
            } else {
                pos.setIndex(0);
                return false;
            }

        }

        String getString() {

            return searchString;

        }

    }

    private static class Search {

        private final List<SearchString> searches;
        private final List<SearchString> positives;

        Search(final List<SearchString> searches) {

            this.searches = searches;
            positives = new ArrayList<SearchString>();

        }

        void search(final Reader reader) throws IOException {

            int current;

            while((current = reader.read()) != -1 && !searches.isEmpty()) {

                char c = (char)current;

                for(final Iterator<SearchString> it = searches.iterator(); it.hasNext();) {
                    final SearchString searchString = it.next();
                    final boolean matches = searchString.checkNextChar(c);
                    if(matches) {
                        positives.add(searchString);
                        it.remove();
                    }
                }

            }

        }

        boolean hasPositives() {

            return !positives.isEmpty();

        }

        void printPositives() {

            for(final Iterator<SearchString> it = positives.iterator(); it.hasNext();) {
                final SearchString searchString = it.next();
                System.out.print(searchString.getString());
                if(it.hasNext())
                    System.out.print(", ");
            }

        }

    }

}

好吧,它不是 100% 可靠,但它是一个开始。

编辑:或者你可以使用像 KayKay 建议的扫描仪,但这有什么乐趣:D

Tadaaaa!

package textsearch;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TextSearch {

    public static void main(final String[] args) throws Exception {

        final URL testFileURL = Thread.currentThread().getContextClassLoader().getResource("textsearch/test.txt");
        final File input = new File(testFileURL.toURI());
        final FileReader reader = new FileReader(input);

        final SearchString search1 = new SearchString("Cell");
        final SearchString search2 = new SearchString("Engine");

        final List<SearchString> searches = new ArrayList<SearchString>();
        searches.add(search1);
        searches.add(search2);

        final Search search = new Search(searches);

        try {
            search.search(reader);
        } finally {
            reader.close();
        }

        if(search.hasPositives()) {
            System.out.print("File " + input.getName() + " contains the words ");
            search.printPositives();
            System.out.println("");
        } else {
            System.out.println("File " + input.getName() + " didn't contain any of the search terms.");
        }

    }

    private static class SearchString {

        final String searchString;
        final ParsePosition pos;

        SearchString(final String searchString) {

            if(searchString == null || searchString.isEmpty())
                throw new IllegalArgumentException("I can't search for nothing!");

            this.searchString = searchString;
            pos = new ParsePosition(0);

        }

        boolean checkNextChar(final char c) {

            if(searchString.charAt(pos.getIndex()) == c) {
                pos.setIndex(pos.getIndex() + 1);
                if(pos.getIndex() >= searchString.length()) {
                    pos.setIndex(0);
                    return true;
                }
                return false;
            } else {
                pos.setIndex(0);
                return false;
            }

        }

        String getString() {

            return searchString;

        }

    }

    private static class Search {

        private final List<SearchString> searches;
        private final List<SearchString> positives;

        Search(final List<SearchString> searches) {

            this.searches = searches;
            positives = new ArrayList<SearchString>();

        }

        void search(final Reader reader) throws IOException {

            int current;

            while((current = reader.read()) != -1 && !searches.isEmpty()) {

                char c = (char)current;

                for(final Iterator<SearchString> it = searches.iterator(); it.hasNext();) {
                    final SearchString searchString = it.next();
                    final boolean matches = searchString.checkNextChar(c);
                    if(matches) {
                        positives.add(searchString);
                        it.remove();
                    }
                }

            }

        }

        boolean hasPositives() {

            return !positives.isEmpty();

        }

        void printPositives() {

            for(final Iterator<SearchString> it = positives.iterator(); it.hasNext();) {
                final SearchString searchString = it.next();
                System.out.print(searchString.getString());
                if(it.hasNext())
                    System.out.print(", ");
            }

        }

    }

}

Alright, it ain't 100% reliable, but it's a start.

EDIT: or you can use a Scanner like KayKay suggested, but where's the fun in that :D

与风相奔跑 2024-12-19 00:58:51

虽然我不确定我是否理解你的问题,但这里有一些提示。

要获取类名,请使用 obj.getClass().getName()。
要搜索字符串,请使用 str.contains("Cell") 或使用正则表达式。看一下 java.util.Pattern 类。

Although I am not sure I understand your question here are some tips.

To get class name use obj.getClass().getName().
To search into string use str.contains("Cell") or use regular expressions. Take a look on class java.util.Pattern.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文