问题4.使用a编写一个创建新单词列表的循环 用于从问题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
此代码有效,但只删除引号。如何删除其他形式的标点符号?
答案 0 :(得分:1)
你有一个for循环。问题是,如果在循环内执行x = y.replace(foo,bar),则每次都会覆盖x。如果你使用text = text.replace(i,“”),那将逐步删除标点符号。
答案 1 :(得分:1)
首先,这些引文不是本文的一部分。这就是如何定义此字符串变量。因此,您只在这里查看,
和.
。您可以通过逐字打印文本来清楚地看到它:
for word in listWords:
print word
删除任何标点符号:
''.join(x for x in text if x not in string.punctuation)
答案 2 :(得分:0)
首先从句子中删除标点符号然后再将单词拆分可能更简单。例如:
import string
text = ("There once was a man in Idaho, he invented the potato.")
out = text.translate(string.maketrans("",""), string.punctuation)
listWords = text.split()