Python编写一个循环,创建一个新单词列表,使用string方法从列表中删除单词

Python编写一个循环,创建一个新单词列表,使用string方法从列表中删除单词,python,Python,问题4。编写一个循环,使用 string方法从问题3中创建的列表中删除单词 所有的前导和尾随标点符号。提示:字符串库, 上面导入的,包含一个名为标点符号的常量。 三行代码 好的,我已经完成了如下代码: import string text = ("There once was a man in Idaho, he invented the potato.") listWords = text.split() #problem3 for i in string.punctuation: l

问题4。编写一个循环,使用 string方法从问题3中创建的列表中删除单词 所有的前导和尾随标点符号。提示:字符串库, 上面导入的,包含一个名为标点符号的常量。 三行代码

好的,我已经完成了如下代码:

import string
text = ("There once was a man in Idaho, he invented the potato.")
listWords = text.split() #problem3
for i in string.punctuation:
    listWords = text.replace(i,"") #problem4

这段代码可以工作,但它只删除引号。如何删除其他形式的标点符号?

您有一个for循环。问题是,如果在循环中执行x=y.replace(foo,bar),则每次都会覆盖x。如果您使用text=text.replace(i,“”),则会逐渐删除标点符号。

首先从句子中删除标点符号,然后将单词拆分可能更简单。例如:

import string
text = ("There once was a man in Idaho, he invented the potato.")
out = text.translate(string.maketrans("",""), string.punctuation)
listWords = text.split()

首先,这些引文不是本文的一部分。这就是这个字符串变量的定义方式。因此,您只能在这里查看
。通过逐字打印文本,您可以清楚地看到它:

for word in listWords:
    print word
要删除任何标点符号,请执行以下操作:

''.join(x for x in text if x not in string.punctuation)

您的可能副本已具有for循环。只要把你的代码和链接的副本结合起来就可以了。另一方面,您的代码不能按原样工作。