Search code examples
pythonnltk

asking user to enter the text file name


i have this python code which make stemming for lists of words form text file and save the results to another text file ,but I want to adjust the code by the following :

  1. aske the user to enter the full path of the input(words text file)

  2. save the output(original words + stemmed words) in full path text file that the user enter it

    import nltk
    from nltk.stem import PorterStemmer
    from nltk.stem import LancasterStemmer
    from nltk.stem.porter import PorterStemmer
    stemmer = PorterStemmer()
    with open(r'C:\Users\hp\Desktop\Final Project\now.txt', 'r') as fp:
    tokens = fp.readlines()
    for t in tokens:
     s = stemmer.stem(t.strip())
     print(s, file=open("output.txt", "a"))
    

any help?


Solution

  • from nltk.stem.porter import PorterStemmer
    
    stemmer = PorterStemmer()
    
    input_path = input("Please type the path of the input file: ")
    output_path = input("Please type the path of the output file: ")
    
    with open(input_path, 'r') as fp:
        tokens = fp.readlines()
    
    for t in tokens:
        s = stemmer.stem(t.strip())
        print(f"{t.strip()} {s}", file=open(output_path, "a"))
    
    

    Explanation:

    • the input function prints a prompt (the strings it receives as parameters) and waits for an input, which it returns.
    • the with statement is used for context management and will lead to the open file being automatically closed when we exit the context. The code to be executed within this context must be indented. You can read more here.
    • the for loop requires that the code being looped is indented.
    • to elegantly show the words and their stems one after another, f-strings were used. The .strip() function removes whitespace - this means it will remove any spaces or newlines in the given strings.
    • finally, most of the imports were not needed for the code to run, so they were removed.