Python 如何去除文件中的单词
我是python和一般编程的初学者。 我正试图清除文本文件中的某些单词。我有一个.txt文件,其中有我在第一个文本文件中试图删除的单词。 我的代码现在看起来像这样,但它没有按预期的方式工作:Python 如何去除文件中的单词,python,dictionary,Python,Dictionary,我是python和一般编程的初学者。 我正试图清除文本文件中的某些单词。我有一个.txt文件,其中有我在第一个文本文件中试图删除的单词。 我的代码现在看起来像这样,但它没有按预期的方式工作: commonWords = "common.txt" commonFile = open(commonWords, "r").read() for cw in "commonWords": text = text.replace(cw, " ") 有什么办法可以使这项工作顺利进行吗?您忘了从文件
commonWords = "common.txt"
commonFile = open(commonWords, "r").read()
for cw in "commonWords":
text = text.replace(cw, " ")
有什么办法可以使这项工作顺利进行吗?您忘了从文件中提取单词:
filepath = "common.txt"
words_file_content = open(filepath, "r").read()
words = set(words_file_content.split()) # get separate words from file
for word in words:
text = text.replace(word, "")
您需要再次将更改写入文件以保留它们。text=text.replacecw,os仅在此脚本范围内更改文本,除非再次保存,否则更改不会反映在文件中。这些特定单词是什么?顺便说一句,您正在迭代字符串commonWords的每个字符,我不知道这是否是您想要实现的行为。