在Python中删除列表中的标点符号
创建一个Python程序,将字符串转换为列表,使用循环删除任何标点符号,然后将列表转换回字符串,并打印不带标点符号的句子在Python中删除列表中的标点符号,python,list,loops,punctuation,Python,List,Loops,Punctuation,创建一个Python程序,将字符串转换为列表,使用循环删除任何标点符号,然后将列表转换回字符串,并打印不带标点符号的句子 punctuation=['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"] str=input("Type in a line of text: ") alist=[] alist.extend(str) print(alist) #Use loop to remove any punctuation (tha
punctuation=['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"]
str=input("Type in a line of text: ")
alist=[]
alist.extend(str)
print(alist)
#Use loop to remove any punctuation (that appears on the punctuation list) from the list
print(''.join(alist))
这就是我目前所拥有的。我试着使用类似于:
alist.remove(标点符号)
的东西,但我在说类似于list.remove(x):x不在列表中时出错。起初我没有正确地阅读这个问题,意识到我需要通过使用循环来实现这一点,所以我添加了这个作为评论,现在我被卡住了。但是,我成功地将其从列表转换回字符串。我找到了一种简单的方法:
punctuation=['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"]
result = ""
for character in str:
if(character not in punctuation):
result += character
print result
punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"]
str = raw_input("Type in a line of text: ")
for i in punctuation:
str = str.replace(i,"")
print str
用这种方法你不会得到任何错误
import string
punct = set(string.punctuation)
''.join(x for x in 'a man, a plan, a canal' if x not in punct)
Out[7]: 'a man a plan a canal'
说明:字符串。标点符号预定义为:
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
“!"#$%&\'()*+,-./:;?@[\\]^_`{|}~'
剩下的是一个简单的理解。一个集合
用于加快过滤步骤。下面是如何使用python标记给定语句的答案。我使用的python版本是3.4.4
假设我有保存为1.txt的文本。然后我将python程序保存在文件所在的目录(即1.txt)中。以下是我的python程序:
以open('one.txt','r')作为myFile:
str1=myFile.read()
打印(str1)#这是用标点符号打印给定语句(在删除标点符号之前)
#下面是我们需要删除的标点符号列表,如果我忘记了,请添加更多标点符号
标点符号=['('、')'、'?'、':'、';'、'、'、'、'、'、'、'、'!'、'/'、'、'“、'”]
对于标点符号中的i:
str1=str1。替换(i,“”)#以清空标点符号所在的位置。
myList=[]
myList.extend(str1.split(“”)
打印(str1)#这是打印给定的语句而不使用puctions(删除标点后)
对于myList中的i:
#打印(“打印”)
打印(i,end='\n')
打印(“打印”)
===============下一步我将为您发布如何删除停止词============
在此之前,请允许您评论它是否有用。
谢谢只需使用replace
或strip
。尝试使用replace
或strip
我假设这是一个类,他们必须使用基于问题的循环,它在列表上重复了很多次,这对于非常大的输入可能会很烦人,但很好。:)我会将集合
从genexp中拉出;否则,您将为每个x
构建它。请理解,它是什么意思从genexp中拉出集合?你能给我举个例子吗?@Kyrol,谢谢。几个星期以来我一直在用Python编程