【问题标题】:How do I edit a specific word in my text document?如何编辑文本文档中的特定单词?
【发布时间】:2017-03-23 21:13:22
【问题描述】:

到目前为止,我的代码仅在单词被回车分隔时才编辑它们。如果我通过空格或逗号分隔单词,它们不会被替换。

例如如果我在一行上有“嘿”,在下一行有“嗨”。如果我愿意,我的代码可以同时替换它们。但是,如果我在一行中有“hey”,并且“hi”在“hey”旁边用逗号分隔,我的代码也不会替换。

我的代码的目标是替换 .CSV 文件中的单词,但如果我的代码无法替换以逗号或空格分隔的单词,那么它就不起作用。

这是我的代码,只需按一下按钮即可激活:

try{
    // Input the file location into Path variable 'p'
    Path p = Paths.get("test test.txt");
    //Path p = Paths.get("tiger.csv");

    //Read the whole file to a ArrayList
    List<String> fileContent = new ArrayList<>(Files.readAllLines(p));

    //Converting user input from editSerialField to a string
    String strSerial = editSerialField.getText();
    //Converting user input from editLocationField to a string
    String strLocation = editLocationField.getText();

    //This structure looks for a duplicate in the text file, if so, replaces it with the user input from editLocationField.
    for (int i = 0; i < fileContent.size(); i++)
    {
        if (fileContent.get(i).equals(strSerial))
        {
            fileContent.set(i, strLocation);
            break;
        }

    }

    // write the new String with the replaced line OVER the same file
    Files.write(p, fileContent);

    }catch(IOException e)
    {
        e.printStackTrace();
    }

如何编辑以逗号或空格分隔的单词?另外,如果我可以替换单词,无论它们是大写还是小写,那会很整洁,我该如何执行?

谢谢。

【问题讨论】:

  • 看来您只是将 /entire lines/ 与已知字符串进行匹配,而您说您正在尝试替换单个单词。当然,您必须查看该行并挑选出单词来替换单个单词。考虑使用 Scanner 类或 CSV 解析器,而不是自己进行字符串操作...
  • 当我使用Scanner 时,它无法转换为“路径”。 List&lt;String&gt; fileContent = new ArrayList&lt;&gt;(Files.readAllLines(s)); 而“s”是Scanner s = new Scanner("test test.txt");。我是否打算以不同的方式使用 Scanner 来读取整个文件?
  • 扫描仪功能取代了Files.readAllLines()Scanner 进行读取。见docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
  • 看来我必须为这个 Scanner 函数重新编写我的代码。感谢您的帮助。

标签: java csv arraylist replace


【解决方案1】:

使用正则表达式:

fileContent.replaceAll(s -> s.replaceAll("(?i)\\b" + strSerial + "\\b", strLocation));

在搜索词的两端添加\b,意思是“单词边界”,意味着只有整个单词会被替换。

添加(?i) 表示“忽略大小写”。

【讨论】:

    【解决方案2】:

    在您的代码中,您有以下内容:

    //Read the whole file to a ArrayList
    List<String> fileContent = new ArrayList<>(Files.readAllLines(p));
    

    我猜你的意思是这样的:

    //Read the whole file to a ArrayList
    List<String> fileContent = Files.readAllLines(p);
    

    然后,在遍历每一行时,只需检查每一行是否包含您感兴趣的内容。您也可以将每一行拆分为单词,然后使用 java 8 流检查每个单词。

    【讨论】:

    • 不,他绝对不能。这将替换单词中的 /substrings/ 以及整个单词。
    • 正确。他需要将每一行拆分成单词,然后根据需要进行更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    相关资源
    最近更新 更多