如何计算字符串在CSV文件中出现的次数?

huangapple go评论61阅读模式
英文:

How to count the amount of times a string appears in csv file?

问题

我想要统计在CSV文件中特定单词出现的次数,但我的代码不起作用,不幸的是,由于某种原因,我的调试在eclipse中无法工作,所以很难确定发生了什么。我可能走错了方向,但如果有人有经验,我会感激任何人的建议。这是我一直在尝试让它工作的方式。

FileReader po = new FileReader("filename");
Scanner underinvscan = new Scanner(po);

for (int i = 0; i < file.size(); i++) {
    String string = file.get(i).LOC;
    if (!(string.contains("Under investigation"))) {
        int count = 0;
        count++;

        System.out.println("there have been" + count + "under investigations");
    }
}
英文:

I want to count the amount of times a certain word comes up in a CSV file, my code isnt working and unfortunately for some reason my debug wont work in eclipse so its hard to tell whats happening. I'm probably going about this wrong but if anyone has experience I would appreciate anyones input. this is how ive been trying to get it to work.

FileReader po = new FileReader(&quot;filename&quot;);
			Scanner underinvscan = new Scanner(po);
			
			
			for (int i = 0; i &lt; file.size(); i++) {
				String string = file.get(i).LOC;
				if (!(string.contains(&quot;Under investigation&quot;))) {
					int count = 0; count++;
				
					System.out.println(&quot;there have been&quot; + count + &quot;under investigations&quot;);
				
			
					}
				}
			}
		
	}

答案1

得分: 3

你需要将计数器移到循环外部,这样它就不会在每次循环中被重置:

int count = 0; 
for (int i = 0; i < file.size(); i++) {
    String string = file.get(i).LOC;
    if (!(string.contains("Under investigation"))) {
        count++;
    }
}
System.out.println("已经有" + count + "个调查进行中");

而且可能需要更改条件吗如果你想要计算包含 "Under investigation" 的字符串你需要从条件中删除 `!`,目前你正在计算不包含 "Under investigation" 的字符串

<details>
<summary>英文:</summary>

You need to move the counter outside of the loop, so it is not reset in every loop:

            int count = 0; 
            for (int i = 0; i &lt; file.size(); i++) {
                String string = file.get(i).LOC;
                if (!(string.contains(&quot;Under investigation&quot;))) {
                    count++;
                }
            }
            System.out.println(&quot;there have been&quot; + count + &quot;under investigations&quot;);

And possible the condition? If you want to count the strings that contain the &quot;Under investigation&quot; you need to remove the `!` from the condition, currently you are counting the strings that do not contain the &quot;Under investigation&quot;.

</details>



huangapple
  • 本文由 发表于 2020年8月6日 01:45:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63270761.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定