如何摆脱fi中的单词

2024-05-26 22:56:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python和编程的初学者。 我在试着去掉文本文件中的某些单词。我有一个.txt文件,里面有我在第一个文本文件中要删除的单词。 我的代码现在看起来是这样的,但它没有按预期的方式工作:

commonWords = "common.txt"
commonFile = open(commonWords, "r").read()

for cw in "commonWords":
    text = text.replace(cw, " ")

有什么办法让这一切顺利吗?你知道吗


Tags: 文件代码texttxtread编程方式common
1条回答
网友
1楼 · 发布于 2024-05-26 22:56:08

你忘了从文件中提取单词:

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, "")

相关问题 更多 >

    热门问题