someone can help me with code?
How to search in text file any word and count how many it were repeated?
For example test.txt:
hi
hola
hey
hi
bye
hoola
hi
And if I want to know how many times are repeated in test.txt word "Hi" program must say "3 times repeated"
I hope you understood what I want, thank you for answers.
public int countWord(String word, File file) {
int count = 0;
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(word))
count++;
}
return count;
}
HashMap h=new HashMap();
FileInputStream fin=new FileInputStream("d:\\file.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(fin));
String n;
while((n=br.readLine())!=null)
{
if(h.containsKey(n))
{
int i=(Integer)h.get(n);
h.put(n,(i+1));
}
else
h.put(n, 1);
}
now iterate through this map to get the count for each word using each word as a key to the map values
Apache Commons - StringUtils.countMatches()
Use MultiSet collection from google guava library.
Multiset<String> wordsMultiset = HashMultiset.create();
Scanner scanner = new Scanner(fileName);
while (scanner.hasNextLine()) {
wordsMultiset.add(scanner.nextLine());
}
for(Multiset.Entry<String> entry : wordsMultiset ){
System.out.println("Word : "+entry.getElement()+" count -> "+entry.getCount());
}
package File1;
import java.io.BufferedReader;
import java.io.FileReader;
public class CountLineWordsDuplicateWords {
public static void main(String[] args) {
FileReader fr = null;
BufferedReader br =null;
String [] stringArray;
int counLine = 0;
int arrayLength ;
String s="";
String stringLine="";
try{
fr = new FileReader("F:/Line.txt");
br = new BufferedReader(fr);
while((s = br.readLine()) != null){
stringLine = stringLine + s;
stringLine = stringLine + " ";/*Add space*/
counLine ++;
}
System.out.println(stringLine);
stringArray = stringLine.split(" ");
arrayLength = stringArray.length;
System.out.println("The number of Words is "+arrayLength);
/*Duplicate String count code */
for (int i = 0; i < arrayLength; i++) {
int c = 1 ;
for (int j = i+1; j < arrayLength; j++) {
if(stringArray[i].equalsIgnoreCase(stringArray[j])){
c++;
for (int j2 = j; j2 < arrayLength; j2++) {
stringArray[j2] = stringArray[j2+1];
arrayLength = arrayLength - 1;
}
}//End of If block
}//End of Inner for block
System.out.println("The "+stringArray[i]+" present "+c+" times .");
}//End of Outer for block
System.out.println("The number of Line is "+counLine);
System.out.println();
fr.close();
br.close();
}catch (Exception e) {
e.printStackTrace();
}
}//End of main() method
}//End of class CountLineWordsDuplicateWords
package somePackage;
public static void main(String[] args) {
String path = ""; //ADD YOUR PATH HERE
String fileName = "test2.txt";
String testWord = "Macbeth"; //CHANGE THIS IF YOU WANT
int tLen = testWord.length();
int wordCntr = 0;
String file = path + fileName;
boolean check;
try{
FileInputStream fstream = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while((strLine = br.readLine()) != null){
//check to see whether testWord occurs at least once in the line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if(check){
//get the line, and parse its words into a String array
String[] lineWords = strLine.split("\\s+");
for(String w : lineWords){
//first see if the word is as least as long as the testWord
if(w.length() >= tLen){
/*
1) grab the specific word, minus whitespace
2) check to see whether the first part of it having same length
as testWord is equivalent to testWord, ignoring case
*/
String word = w.substring(0,tLen).trim();
if(word.equalsIgnoreCase(testWord)){
wordCntr++;
}
}
}
}
}
System.out.println("total is: " + wordCntr);
//Close the input stream
br.close();
} catch(Exception e){
e.printStackTrace();
}
}
public class Wordcount
{
public static void main(String[] args)
{
int count=0;
String str="hi this is is is line";
String []s1=str.split(" ");
for(int i=0;i<=s1.length-1;i++)
{
if(s1[i].equals("is"))
{
count++;
}
}
System.out.println(count);
}
}
You can read text file line by line. I assume that each line can contain more than one word. For each line, you call:
String[] words = line.split(" ");
for(int i=0; i<words.length; i++){
if(words[i].equalsIgnoreCase(searhedWord))
count++;
}
try using java.util.Scanner.
public int countWords(String w, String fileName) {
int count = 0;
Scanner scanner = new Scanner(inputFile);
scanner.useDelimiter("[^a-zA-Z]"); // non alphabets act as delimeters
String word = scanner.next();
if (word.equalsIgnoreCase(w))
count++;
return count;
}
Try it this way with Pattern and Matcher.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Dem {
public static void main(String[] args){
try {
File f = new File("d://My.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = new String();
while((s=br.readLine())!=null){
s = s + s;
}
int count = 0;
Pattern pat = Pattern.compile("it*");
Matcher mat = pat.matcher(s);
while(mat.find()){
if(mat.find()){
mat.start();
count++;
}
}
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.util.*;
class filedemo
{
public static void main(String ar[])throws Exception
BufferedReader br=new BufferedReader(new FileReader("c:/file.txt"));
System.out.println("enter the string which you search");
Scanner ob=new Scanner(System.in);
String str=ob.next();
String str1="",str2="";
int count=0;
while((str1=br.readLine())!=null)
{
str2 +=str1;
}
int index = str2.indexOf(str);
while (index != -1) {
count++;
str2 = str2.substring(index + 1);
index = str2.indexOf(str);
}
System.out.println("Number of the occures="+count);
}
}
package com.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws Exception{
BufferedReader bf= new BufferedReader(new FileReader("src/test.txt"));
Scanner sc = new Scanner(System.in);
String W=sc.next();
//String regex ="[\\w"+W+"]";
int count=0;
//Pattern p = Pattern.compile();
String line=bf.readLine();
String s[];
do
{
s=line.split(" ");
for(String a:s)
{
if(a.contains(W))
count++;
}
line=bf.readLine();
}while(line!=null);
System.out.println(count);
}
}
public int occurrencesOfHi()
{
String newText = Text.replace("Hi","");
return (Text.length() - newText.length())/2;
}
Related
I'm trying to develop a hangman as an assignment, and is unable to get one random word from a Text file(which has various words and each word is separated with a space). I've written a code to get a random word, but unable to pick one words and replace it, with the sample string (String w = "this";) i have in the "Function()".
public String randomWord(String wordran) {
try {
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt"));
String line = reader.readLine();
List<String> words = new ArrayList<String>();
while (line != null) {
String[] wordline = line.split(" ");
for (String word : wordline) {
words.add(word);
}
Random rand = new Random();
String randomWord1 = words.get(rand.nextInt(words.size()));
//System.out.println("rand word : " + randomWord1);
}
reader.close();
} catch (Exception e) {
}
return wordran;
}
public void function(){
int numGuesses = 10;
String w = randomWord();
String[] word = w.split("");
ArrayList< String> wList = new ArrayList<>(Arrays.asList(word));
ArrayList< String> wAnswer = new ArrayList< String>(wList.size());
for (int i = 0; i < wList.size(); i++) {
wAnswer.add("_ ");
}
int left = wList.size();
Scanner scanner = new Scanner(System.in);
boolean notDone = true;
ArrayList< String> lettersGuessed = new ArrayList< String>();
while (notDone) {
System.out.println();
String sOut = "";
List< String> lettersLeft = getRemainingLetters(lettersGuessed);
for (String s : lettersLeft) {
sOut += s + " ";
}
System.out.println("Letters Left: " + sOut);
sOut = "";
for (int i = 0; i < wList.size(); i++) {
sOut += wAnswer.get(i);
}
System.out.println(sOut + " Guesses left:" + numGuesses);
System.out.print("Enter a letter(* exit): ");
String sIn = scanner.next();
numGuesses--;
if (sIn.equals("*")) {
break;
}
lettersGuessed.add(sIn);
for (int i = 0; i < wList.size(); i++) {
if (sIn.equals(wList.get(i))) {
wAnswer.set(i, sIn);
left--;
}
}
if (left == 0) {
System.out.println("Congradulations you guessed it!");
break;
}
if (numGuesses == 0) {
System.out.println("You failed...:(");
break;
}
}
}
public static void main(String[] args) throws IOException {
Main ma = new Main();
ma.function();
loadWords();
// ma.randomWord();
}
There are three problems with your code:
You don't need to pass the parameter, String wordran to store the random word. A useful parameter can be String path through which you can pass the path of the file to the function.
You've missed reading the content from the file in the loop. You've read just the first line.
You haven't returned the random word which you have calculated by applying Random#nextInt.
On a side note, I recommend you use try-with-resources syntax to get rid of closing BufferedReader explicitly.
Given below is the correct code incorporating these comments:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
public static void main(String[] args) throws IOException {
// Test
System.out.println(getRandomWord("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt"));
}
public static String getRandomWord(String path) throws IOException {
List<String> words = new ArrayList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
String line;
while ((line = reader.readLine()) != null) {
String[] wordline = line.split("\\s+");
for (String word : wordline) {
words.add(word);
}
}
}
Random rand = new Random();
return words.get(rand.nextInt(words.size()));
}
}
Here is the CSV file I am using:
B00123,55
B00783,35
B00898,67
I need to read and store the first value entered in the file e.g. B00123 and store it into an array. A user can add to the file so it is not a fixed number of records.
So far, I have tried this code:
public class ArrayReader
{
static String xStrPath;
static double[][] myArray;
static void setUpMyCSVArray()
{
myArray = new double [4][5];
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "src\\marks.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] InArray = InputLine.split(",");
//copy the content of the inArray to the myArray
for (int x = 0; x < myArray.length; x++)
{
myArray[Rowc][x] = Double.parseDouble(InArray[x]);
}
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (int Rowc = 0; Rowc < 1; Rowc++)
{
for (int Colc = 0; Colc < 5; Colc++)
{
System.out.println(myArray[Rowc][Colc] + " ");
}
System.out.println();
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
This loops round the file but doesn't not populate the array with any data. The outcome is:
****** Setup Array ******
[[D#42a57993
0.0
0.0
0.0
0.0
0.0
There is actually a NumberFormatException happening when in the first row when trying to convert the ID to Double. So I revised the program and it works for me.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class ArrayReader
{
static String xStrPath;
static Map<String,Double> myArray = new HashMap<>();
static void setUpMyCSVArray()
{
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "/Users/admin/Downloads/mark.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] inArray = InputLine.split(",");
//copy the content of the inArray to the myArray
myArray.put(inArray[0], Double.valueOf(inArray[1]));
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
System.out.println(e);
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (String key : myArray.keySet()) {
System.out.println(key + " = " + myArray.get(key));
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
Output:
the code can't reader anything ,you file path incorrect.give it absoulte file path.
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
I use opencsv library to read from csv.
import com.opencsv.CSVReader;
public class CSV {
private static String file = <filepath>;
private static List<String> list = new ArrayList<>();
public static void main(String[] args) throws Exception {
try {
CSVReader reader = new CSVReader(new FileReader(file));
String[] line;
while ((line = reader.readNext()) != null) {
list.add(line[0]);
}
Object[] myArray = list.toArray();
System.out.println(myArray.length);
System.out.println(myArray[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output printed as below
3
B00123
A folder contains number of text files like a.txt, b.txt, c.txt like that more than 30 files I need to search a particular string in the all files the output should come as follows:
a.txt contains your entered string
20
b.txt contains you entered string
30
And so on...
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter String");
String input = sc.nextLine();
double count = 0, countBuffer = 0, countLine = 0;
String lineNumber = ".txt";
File folder = new File("C://Users//Desktop//Santhosh.txt");
BufferedReader br;
String line = " ";
try {
br = new BufferedReader(new FileReader(folder));
try {
while ((line = br.readLine()) != null) {
countLine++;
//System.out.println(line);
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(input)) {
count++;
countBuffer++;
}
}
#santhosh I think you want to search a text in files and count the occurrence of word according to file here is the program that do this:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class TextSearch {
File file;
FileReader reader;
BufferedReader buffReader;
String word;
Scanner scanner;
Map<String, Integer> counter = new TreeMap<String, Integer>();
public TextSearch() {
file = new File("D:\\Backup\\NP\\GN");// This Contain the 30 files
scanner = new Scanner(System.in);
System.out.println("Enter a word");
word = scanner.nextLine();
File[] listOfFiles = file.listFiles();
startSearch(listOfFiles);
Iterator<String> iterator = counter.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println(key + " contain this word " + word + " " + counter.get(key) + "times");
}
}
public void startSearch(File[] list) {
for (int i = 0; i < list.length; i++) {
if (list[i].isFile()) {
try {
reader = new FileReader(list[i]);
buffReader = new BufferedReader(reader);
String line = "";
while ((line = buffReader.readLine()) != null) {
if (line.contains(word)) {
if (counter.containsKey(list[i].getName())) {
Integer count = counter.get(list[i].getName());
count++;
counter.put(list[i].getName(), count);
} else {
counter.put(list[i].getName(), 1);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String args[]) {
new TextSearch();
}
}
I have a problem. I need to use the first row of the txt as my string and then look in the same txt the occurrences and print the number, but I have a problem, for example; if my txt is like: wordwordword and my string is word, it only counts the first word, it does´t print the counter: 3, print the counter: 1. How can I solve this?
Demo.java
import java.io.*;
import java.util.*;
public class Demo {
public static void main(String args[]) throws java.io.IOException {
BufferedReader in = new BufferedReader(new FileReader("c.txt"));
Scanner sc = new Scanner(System.in);
String s1;
s1 = in.readLine();
String Word;
Word = s1;
String line = in.readLine();
int count = 0;
String s[];
do {
s = line.split(" ");
for (int i = 0; i < s.length; i++) {
String a = s[i];
if (a.contains(Word))
count++;
}
line = in.readLine();
} while (line != null);
System.out.println("first line: " + s1);
System.out.print("There are " + count + " occurences of " + Word
+ " in ");
java.io.File file = new java.io.File("c.txt");
Scanner input = new Scanner(file);
while (input.hasNext()) {
String word = input.nextLine();
System.out.print(word);
}
}
}
txt:
GAGCATAGA
CGAGAGCATATAGGAGCATATCTTGAGCATACCGAGCATATGAGCATAATATACCCGTCCGAGAGCATACACTGAGCATAAAGGAGCATAGAGCATACAACTGAGAATGGAGCATAGAGCATACGGAGCATAAGAGCATAGAGCATAGAGCATACGGAGCATAGAGCATAGAGCATAGCCGATGGGGAGCATACTGTTACGTAGAGCATACGAGCATAGCGCAAGAGCATAAAGAGCATAGAGCATATGAGCATATAGAGCATACGAGCATACAAGATCCGGGGAGCATAGCGAGGTAATAGTCGGAGCATAGAGCATAGAGCATATGAGCATACGGGAGCATAAATGAGCATAAGGAGCATAGAGCATAGAGCATAAGAGCATATCTCGAGCATAAGCGAGCATAGAGCATAAAAATCAATCACGTTGAGCATATGAGCATAAATACTGGAGCATAGATCGAGCATAGTAGAGCATACGAGCATAGAGCATAGGAGCATAAGAGCATATGAGCATATTGAGCATATGAAGGAGCATAAAAATGAGCATAAGGAGCATACCATCGTTGAGCATAATCCGAGCATAGGAGCATAGAATAGAGCATAGACAGGAGTTTTTGGAGCATATGAGCATAGAGCATAGAGCATAGAGCATAGAGCATAGAGCATAGAGCATATTCGAGCATAATTGAGCATATGAGCATAGAGCATATGGAGCATAGGCTGAGCATACCGAGCATAGCAATTAGAGCATAATCCTAGGGAGCATAGGAGCATACGTGAGCATAGCTGAGCATAGAGCATAGAGCATAGTGTTCGAGCATAGAGCATAGAGCATATGAGCATAGAGCATACTTGAGCATATGGTACGAGCATAGGAGCATATAAGGAGGAGCATATCGAGCATAGAGCATAGGCCTGGCCAGAGCATATAACCGAGCATAGGGTTGGAGCATAAGGCCGGAGCATACGAGCATACGAGCATATGAAATGAGCATAATGTGAGCATAGAGCATATCGAGCATATGAGCATAGGAGCATA
in this example with the txt, the program should print the counter= 21
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Match {
public static String TEXT_FILE_LOCATION="input.txt";
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File(TEXT_FILE_LOCATION));
String stringToSearch=in.nextLine();
StringBuffer buffer=new StringBuffer();
for(;in.hasNext();){
buffer.append(in.next());
}
Pattern pattern = Pattern.compile(stringToSearch);
Matcher matcher = pattern.matcher(buffer.toString());
int from = 0;
int count = 0;
while(matcher.find(from)) {
count++;
from = matcher.start() + 1;
}
System.out.println("Number of matches : "+count);
}
}
You can do it by looping through your text then match the string with part of the text.
Here it is:
public static void main(String[] args) {
String word = "word";
String text = "wordwordword";
int count = 0;
for(int i =0 ; i <text.length() ; i++){
for(int j = 0 ; j < word.length();j++){
if((j+i)>=text.length())break;
if(word.charAt(j)!=text.charAt(j+i))break;
if(j==word.length()-1)count++;
}
}
System.out.println(count);//prints 3
}
Also you could use .toCharArray() to get the characters in the string before looping to enhance the performance.
Here is the modified code for that :
public static void main(String[] args) {
char[] word = "word".toCharArray();
char[] text = "wordwordword".toCharArray();
int count = 0;
for(int i =0 ; i <text.length ; i++){
for(int j = 0 ; j < word.length;j++){
if((j+i)>=text.length)break;
if(word[j]!=text[j+i])break;
if(j==word.length-1)count++;
}
}
System.out.println(count);
}
I'm trying to count the number of Words, Lines and characters(excluding whitespace). The only part I can't get to work is ignoring the whitespace for the character count.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Exercise2 {
public static void main(String[] args) throws IOException{
File file = getValidFile();
int count = wordCount(file);
int lines = lineCount(file);
int characters = characterCount(file);
System.out.println("Total Words = " + count);
System.out.println("Total Lines = " + lines);
System.out.println("Total Characters = " + characters);
}
public static int characterCount(File file) throws IOException {
{
Scanner inputFile = new Scanner(file).useDelimiter(",\\s*");;
int characters = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.next(); //read in a word
characters++; //count the word
}
inputFile.close();
return characters;
}
}
public static int lineCount(File file)throws IOException {
{
Scanner inputFile = new Scanner(file);
int lines = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.nextLine(); //read in a line
lines++; //count the line
}
inputFile.close();
return lines;
}
}
public static int wordCount(File file) throws IOException {
{
Scanner inputFile = new Scanner(file);
int count = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.next(); //read in a word
count++; //count the word
}
inputFile.close();
return count;
}
}
public static File getValidFile()
{
String filename; // The name of the file
File file;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get a valid file name.
do
{
/*for (int i = 0; i < 2; i ++ )
{*/
System.out.print("Enter the name of a file: ");
filename = keyboard.nextLine();
file = new File(filename);
if (!file.exists())
System.out.println("The specifed file does not exist - please try again!");
}while( !file.exists());
return file;
}
}
If you want to count the characters in the file, excluding any whitespace, you can read your file line by line and accumulate the character count, or read the whole file in a String and do the character count, e.g.
String content = new Scanner(file).useDelimiter("\\Z").next();
int count = 0;
for (int i = 0; i < content.length(); i++) {
if (!Character.isWhitespace(content.charAt(i))) {
count++;
}
}
System.out.println(count);
EDIT
Other solutions if you don't care about the content of the file, then there is no need to load it into a String, you can just read character by character.
Example counting the non-whitespace characters in Arthur Rimbaud poetry.
Using a Scanner
URL rimbaud = new URL("http://www.gutenberg.org/cache/epub/29302/pg29302.txt");
int count = 0;
try (BufferedReader in = new BufferedReader(new InputStreamReader(rimbaud.openStream()))) {
int c;
while ((c = in.read()) != -1) {
if (!Character.isWhitespace(c)) {
count++;
}
}
}
System.out.println(count);
Using a plain StreamReader
count = 0;
try (Scanner sin = new Scanner(new BufferedReader(new InputStreamReader(rimbaud.openStream())))) {
sin.useDelimiter("");
char c;
while (sin.hasNext()) {
c = sin.next().charAt(0);
if (!Character.isWhitespace(c)) {
count++;
}
}
}
System.out.println(count);