Python 不删除单词,但适用于单个字母
我有一个项目,我应该使用下面的代码从语句中删除一些单词:
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)
输出:'因此从现有的推论中得出了这个结论'
预期输出:'因此给我们带来了这个结论现有的推论'
我不知道为什么,但它适用于单个字母而不是单个单词,假设下面的代码:
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 so his onlsion from he exising推断'
为什么会发生这种情况?
I have this project where I'm supposed to remove some word from a statement using code below:
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)
Output: 'And thus brought us to this conclusion from the existing inference'
Expected output: 'thus brought us this conclusion existing inference'
I'm not sure why but it works well for single letter but not a single word, suppose the code below:
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)
Output: 'And hs rogh s o his onlsion from he exising inferene'
Why is this happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在空格上拆分
f
以便迭代单词:或者,使用生成器表达式:
You need to split
f
on spaces in order to iterate over the words:Or, with a generator expression:
您必须迭代不在字符串上的字符串列表,如下所示。
You have to iterate over a list of strings not on the string as shown below.