Longest word in a file

Slow because of the gazillion of forks, but pure shell, does not require awk or special bash features:

$ cat /usr/share/dict/words | 
    xargs -n1 -I '{}' -d 'n'   sh -c 'echo `echo -n "{}" | wc -c` "{}"' | 
    sort -n | tail
23 Pseudolamellibranchiata
23 pseudolamellibranchiate
23 scientificogeographical
23 thymolsulphonephthalein
23 transubstantiationalist
24 formaldehydesulphoxylate
24 pathologicopsychological
24 scientificophilosophical
24 tetraiodophenolphthalein
24 thyroparathyroidectomize

You can easily parallelize, e.g. to 4 CPUs by providing -P4 to xargs.

EDIT: modified to work with the single quotes that some dictionaries have. Now it requires GNU xargs because of -d argument.

EDIT2: for the fun of it, here is another version that handles all kinds of special characters, but requires the -0 option to xargs. I also added -P4 to compute on 4 cores:

cat /usr/share/dict/words | tr 'n' '' | 
    xargs -0 -I {} -n1 -P4  sh -c  'echo ${#1} "$1"'  wordcount {} | 
    sort -n | tail

Write a python program to find longest word from text file with Practical Example

Program Logic:

  • Open text file say ‘name.txt’ in read mode using open function
  • Pass file name and access mode to open function
  • Read the whole content of text file using read function and store it in another variable say ‘str’
  • Use split function on str object and store words in variable say ‘words’
  • Find maximum word from words using len method
  • Iterate through word by word using for loop
  • Use if loop within for loop to check the maximum length of word
  • Store maximum length of word in variable say ‘longest_word’
  • Display longst_word using print function

Below is implementation code/Source code

fin = open("name.txt","r")
str = fin.read()
words = str.split()
max_len = len(max(words, key=len))
for word in words:
    if len(word)==max_len:
        longest_word =word
        
print(longest_word)

Below is Output:

Sumedh

Below is Snapshot of Executable code with output

Below is name.txt file

<

To find a word in a file using Python:

  1. Specify a target word.
  2. Open a file.
  3. Loop through the file line by line.
  4. Check if any line has the target word. If it does, print the line number and end the loop.

For example, let’s check where (if any) the word “test” is in a file called “example.txt”.

word = "test"

with open("example.txt", "r") as file:
    for line_number, line in enumerate(file, start=1):  
        if word in line:
          print(f"Word '{word}' found on line {line_number}")
          break

print("Search completed.")

In my case, the word is found in the second line. So the output is:

Word 'test' found on line 2
Search completed.

(The enumerate(file, start=1) matches each line with an index. Line 1 has an index of 1, line 2 has an index of 2, and so on. This simplifies the loop. Check out this article to learn more about enumerating in Python.)

How to Find the Longest Word in a File Using Python

To find the longest word(s) in a file:

  1. Open a file.
  2. Store the words in memory.
  3. Find the longest word.
  4. Find other possible words that are equally long.

For example, let’s find out the longest words in a file called “example.txt”:

with open("example.txt", "r") as file:
    words = file.read().split()

longest_word = max(words, key=len)
longest_words = [word for word in words if len(word) == len(longest_word)]

print(longest_words)

If you are confused, the max() function:

  • Loops through the words
  • Applies len function on each word.
  • Returns the word with the greatest value returned by the len. In other words, the longest word.

Also, learn more about list comprehensions to create shorthand for loops like the one in the last line.

How to Find and Replace a Word in a File Using Python

To find and replace a word in a file with Python:

  1. Open a file.
  2. Read the file in memory.
  3. Find and replace specific words.
  4. Write the fixed-up data back to the file.

Here is an example:

# Read the file in memory
with open("example.txt", "r") as file:
  data = file.read()

# Replace matches
data = data.replace("test", "banana")

# Write the data back to the file
with open("example.txt", "w") as file:
  file.write(data)

Thanks for reading. Happy coding!

Further Reading

  • How to Find All Files With Extension
  • How to Write to a File in Python
  • The with Statement in Python

About the Author

I’m an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.

Recent Posts

In this article, we will show you how to print all the longest words from a given text file using python. The longest words are the words which are having the same length as the longest word (maximum length) in a text file.

Assume we have taken a text file with the name ExampleTextFile.txt consisting of some random text. We will return all the longest words from a given text file.

ExampleTextFile.txt

Good Morning Tutorials Point
This is Tutorials Point sample File
Consisting of Specific
abbreviated
source codes in Python Seaborn Scala
Imagination
Summary and Explanation
Welcome user
Learn with a joy

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the path of the text file.

  • Use the open() function (opens a file and returns a file object as a result) to open the text file in read-only mode by passing the file name, and mode as arguments to it  (Here “r” represents read-only mode).

with open(inputFile, 'r') as filedata:
  • Create a variable to read the text file data using the read() function (reads the specified number of bytes from the file and returns them. The default value is -1, which means the entire file) and split it into a list of words of a given text file using the split() function (splits a string into a list. We can define the separator; the default separator is any whitespace).

  • Find the length of the longest word using the len() (The number of items in an object is returned by the len() method. It returns the number of characters in a string when the object is a string) and max() (returns the highest-valued item, or the highest-valued item in an iterable) functions from the above words list.

len(max(words List, key=len))
  • The key=len specifies that we must obtain the word depending on its length, and we will obtain the maximum length word using the max() function and the length of the maximum length word using the len() function.

  • Using the list comprehension, get all the words with the longest length and save them in another variable. Here we are traversing in each word of the file and checking whether the length of that word is equal to the length of the longest word using the for loop in a list comprehension.

list comprehension:
  • When you wish to build a new list based on the values of an existing list, list comprehension provides a shorter/concise syntax.

  • Print all the longest words from a given text file.

  • Close the input file with the close() function (used to close an opened file).

Example

The following program checks the length of the longest word and prints all the words which are having the same length as that of the longest word from a given text file −

inputFile = "ExampleTextFile.txt" with open(inputFile, 'r') as filedata: wordsList = filedata.read().split() longestWordLength = len(max(wordsList, key=len)) result = [textword for textword in wordsList if len(textword) == longestWordLength] print("The following are the longest words from a text file:") print(result) filedata.close()

Output

On executing, the above program will generate the following output −

The following are the longest words from a text file:
['abbreviated', 'Imagination', 'Explanation']

We read some random text from a text file in this program. We read over the entire file and break it down into words. We determined the length of the maximum length word after we obtained the words. Then we went through the file word by word, checking whether the length of the corresponding word was equal to the length of the minimal length word. If it is true, we will print those words and close the open file.

Conclusion

So, from this article, we learned how to read the entire file content at once, which is useful for searching any word in the entire document rather than searching line by line. We also learned how to split the file content into words using the split() function and determining the length of the shortest word. After determining the maximum length, we learned how to scan the entire file content for the maximum length words.

Hi guys, today we will see how to find the longest word in a text file in C++.

Before we start with this topic, I would like to tell you the methods to read a file.

Methods To Read A File

You can learn about file handling from this website: file handling. I am hereby extending the topic.

We can read a text file in three ways:

  • Character By Character
    char ch;
    while(!f.eof())
    { 
         f.get(ch);
    }
  • Word By Word
    char ch[25];
    while(!f.eof())
    {
         f>>ch;
    }
  • Line By Line
    char ch[100];
    while(!f.eof())
    {
            f.getline(ch,100);
    }

Find The Longest Word

So after discussing the methods to read a file, let’s move ahead to the solution.
In this problem, we will assume that we have a text file named as file.txt containing the following data:

apple
banana
cherry
pineapple
watermelon

So to find the longest word, we will read this text file word by word. After reading a word, we will store that word in a variable ‘ch’. Initially, we will declare an integer variable ‘max’ and assign it with a value equal to zero.
Now, we will calculate the size of each word using the strlen() function and check whether it is greater than the value stored in ‘max’ or not. If the value comes out to be greater than the value of ‘max’ then, we will update the value of ‘max’ with this new value and copy that word in another variable ‘ch1’ using strcpy() function.

This process continues until every word of the text file gets checked.

In the end, we will get the longest word in the variable ‘ch1’ and its length in variable ‘max’.

Code:

ifstream f;
f.open("file.txt");
char ch[100],ch1[100];
int max=0;
while(!f.eof())
{
  f>>ch;
  if(max<strlen(ch))
  {
    max=strlen(ch);
    strcpy(ch1,ch);
  }
}
f.close();
cout<<ch1;

In this code, we are displaying the longest word. So, its output will be

watermelon

We can also display the length of the longest word by printing the value of the variable ‘max’.

Понравилась статья? Поделить с друзьями:
  • Longest word given letters
  • Longest word from these letters
  • Longest word for thank you
  • Longest word for excited
  • Longest word for a lake