user2558831
user2558831

Reputation: 83

searching in text file word list and check all the words that start with each letter I input

So far I got this ...

with open('d:\word_list.txt', 'r') as inF: 
b = input('Enter word: ') 
for letter in b: 
 for item in inF: 
  if item.startswith(letter): 
   print(item) 

If I type "zucaritas", this code only prints those words begining in "z" and not the other letters, the "u", the "c", etc. I want to check all the words from the list that start with each letter I want to type. What can I do? By the way, I'm a beginner in python. Thanks

Upvotes: 0

Views: 1248

Answers (3)

jfs
jfs

Reputation: 414795

You can print all words that start with any letter from a given word in a single pass through the word list from the file:

#!/usr/bin/env python3
letters = tuple(input('Enter word: ')) # startswith() can work with a tuple
with open(r'd:\word_list.txt') as file:
    for word in file:
        if word.startswith(letters): # if word starts with any of the letters
           print(word, end='')

Upvotes: 0

med116
med116

Reputation: 1616

Node JS script

var fs = require("fs");
var letter = process.argv[2];

var writeStream = fs.createWriteStream("./letters/" + letter + ".txt");


fs.createReadStream("./word_list.txt").on("data", function(chunk){
    var words = chunk.toString().split("\n");
    words.forEach(function(word){
        var firstLetter = word.charAt(0);
        if(firstLetter == letter || firstLetter == letter.toUpperCase()){
            console.log(firstLetter);
            writeStream.write(word + "\n");
            console.log("wrote " + word);
        }else{

        }



    });
});

you can call this like node your_script_name.js b to save all the words that begin with b to a file called letters/b.txt

Upvotes: 0

Kevin
Kevin

Reputation: 76254

Iterating through inF the first time exhausts it, and it can't be iterated through again. So the loop will only execute for the first letter in b.

You can get a fresh file object by opening the file repeatedly, for each letter in b:

b = input('Enter word: ') 
for letter in b: 
 with open('d:\word_list.txt', 'r') as inF: 
  for item in inF: 
   if item.startswith(letter): 
    print(item) 

Alternatively, you can manually rewind the file object to its beginning state with seek:

with open('d:\word_list.txt', 'r') as inF: 
 b = input('Enter word: ') 
 for letter in b: 
  inF.seek(0)
  for item in inF: 
   if item.startswith(letter): 
    print(item) 

Upvotes: 2

Related Questions