要求用户输入文本文件名
asking user to enter the text file name
我有这个 python 代码,可以从文本文件中提取单词列表并将结果保存到另一个文本文件,但我想通过以下方式调整代码:
要求用户输入完整的输入路径(words文本文件)
将输出(原始词+词干词)保存在用户输入的完整路径文本文件中
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"))
有什么帮助吗?
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"))
解释:
input
函数打印提示(它接收的字符串作为参数)并等待输入,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
循环要求被循环的代码缩进。
- 为了优雅地依次显示单词和词干,使用了 f-strings。
.strip()
函数删除空格 - 这意味着它将删除给定字符串中的任何空格或换行符。
- 最后,代码 运行 不需要大部分导入,因此它们被删除了。
我有这个 python 代码,可以从文本文件中提取单词列表并将结果保存到另一个文本文件,但我想通过以下方式调整代码:
要求用户输入完整的输入路径(words文本文件)
将输出(原始词+词干词)保存在用户输入的完整路径文本文件中
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"))
有什么帮助吗?
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"))
解释:
input
函数打印提示(它接收的字符串作为参数)并等待输入,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
循环要求被循环的代码缩进。- 为了优雅地依次显示单词和词干,使用了 f-strings。
.strip()
函数删除空格 - 这意味着它将删除给定字符串中的任何空格或换行符。 - 最后,代码 运行 不需要大部分导入,因此它们被删除了。