Home > Software design >  Executing the string in each line of the test.txt file with skip_letter function?
Executing the string in each line of the test.txt file with skip_letter function?

Time:07-21

I have test.txt file, each line of this file has a string. I want the skip_letter function to run for each string. I have 100 strings in txt file. I want output by running these strings one by one in function. I mean: I have a string named banana which is assuming it will be bananna. I just want the bananna to be output.

My code:

import itertools

def skip_letter():
    print("\nSkip Letter:\n")
    for combo in itertools.combinations(keyword, len(keyword) - 1):
        word = "".join(combo)
        print(word)

CodePudding user response:

Give the function a parameter instead of using the global variable keyword. Then call it when you loop over the file contents.

import itertools

def skip_letter(keyword):
    print("\nSkip Letter:\n")
    for combo in itertools.combinations(keyword, len(keyword) - 1):
        word = "".join(combo)
        print(word)

with open('test.txt') as f:
    for line in f:
        line = line.strip()
        skip_letter(line)

CodePudding user response:

Once you have your function defined, you just need to read your txt file and iterate over each one of the lines. Beware that the skip_letter function now has a parameter keyword to let the function know which string needs to use.

import itertools

def skip_letter(keyword):
    print("\nSkip Letter:\n")
    for combo in itertools.combinations(keyword, len(keyword) - 1):
        word = "".join(combo)
        print(word)

file1 = open('test.txt', 'r')
Lines = file1.readlines()
  
for line in Lines:
    skip_letter(line)
  • Related