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 :
aske the user to enter the full path of the input(words text file)
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?
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:
input
function prints a prompt (the strings it receives as parameters) and waits for an input, which it returns.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.for
loop requires that the code being looped is indented..strip()
function removes whitespace - this means it will remove any spaces or newlines in the given strings.