Py学习  »  Python

Python不会删除单词,但适用于单个字母

dan123 • 3 年前 • 1386 次点击  

我有一个项目,我应该使用下面的代码从语句中删除一些单词:

forbidden_words = ["And","is","to","from","the"]
f = "And thus brought us to this conclusion from the existing inference"

h = []
for i in f:
    if i not in forbidden_words:
        h.append(i)
"".join(h)

输出: 'And thus brought us to this conclusion from the existing inference'

预期产出: 'thus brought us this conclusion existing inference'

我不知道为什么,但它适用于单个字母,但不适用于单个单词,假设代码如下:

forbidden_words = ["u","t","c","b","a"]
f = "And thus brought us to this conclusion from the existing inference"

h = []
for i in f:
    if i not in forbidden_words:
        h.append(i)
"".join(h)

输出: 'And hs rogh s o his onlsion from he exising inferene'

为什么会这样?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129817
 
1386 次点击  
文章 [ 3 ]  |  最新文章 3 年前
Dhananjay Yadav
Reply   •   1 楼
Dhananjay Yadav    3 年前
forbidden_words = ["And","is","to","from","the"]
f = "And thus brought us to this conclusion from the existing inference"
for words in forbidden_words:
     f = ''.join(f.split(words))
balu
Reply   •   2 楼
balu    3 年前

您必须遍历字符串列表,而不是如下所示的字符串。

forbidden_words = ["And","is","to","from","the"]
sentence = "And thus brought us to this conclusion from the existing inference".split()

filt_text = [ w  for w in sentence if w not in forbidden_words]

filt_sentence = ' '.join(filt_text)

print(filt_sentence )
ddejohn
Reply   •   3 楼
ddejohn    3 年前

你需要分开 f 在空格上,为了重复单词:

h = []
for word in f.split():
    if word not in forbidden_words:
        h.append(word)
" ".join(h)

或者,使用生成器表达式:

" ".join(word for word in f.split() if word not in forbidden_words)