【问题标题】:Removing punctuation in lists in Python在 Python 中删除列表中的标点符号
【发布时间】:2013-10-25 04:50:29
【问题描述】:

创建一个 Python 程序,将字符串转换为列表,使用循环删除任何标点符号,然后将列表转换回字符串并打印不带标点符号的句子。

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(punctuation) 的东西,但我收到一个错误,比如 list.remove(x): x not in list。一开始我没有正确阅读这个问题,并意识到我需要通过使用循环来做到这一点,所以我将其添加为评论,现在我被卡住了。但是,我成功地将它从列表转换回字符串。

【问题讨论】:

  • 只需使用replacestrip

标签: python list loops punctuation


【解决方案1】:
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'

说明:string.punctuation 预定义为:

'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

剩下的就是直截了当的理解。 set 用于加快过滤步骤。

【讨论】:

  • 我会将set 拉出基因表达式;否则,您将为每个 x 构建它。
  • 只是为了理解,pull the set out of the genexp 是什么意思?可以举个例子吗?
  • @Kyrol 见the set() trap
  • 谢谢。几周以来我一直在用 Python 编程。 ;)
【解决方案2】:

我找到了一个简单的方法:

punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"]
str = raw_input("Type in a line of text: ")

for i in punctuation:
  str = str.replace(i,"")

print str

这样你就不会出错了。

【讨论】:

  • 它会多次迭代列表,这对于非常大的输入可能会很烦人,但很好。 :)
【解决方案3】:
punctuation=['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"]
result = ""
for character in str:
   if(character not in punctuation):
       result += character
print result

【讨论】:

  • 尝试使用replacestrip
  • 我认为这是一个类,他们必须根据问题使用循环
【解决方案4】:

这里是如何使用 python 标记给定语句的答案。我使用的python版本是3.4.4 假设我有保存为 one.txt 的文本。然后我将我的python程序保存在我的文件所在的目录中(即one.txt)。以下是我的python程序:

使用 open('one.txt','r') 作为 myFile: str1=myFile.read() print(str1)# 这是用标点符号打印给定的语句(在删除标点符号之前) # 以下是我们需要删除的标点列表,如果我忘记了再添加 标点符号 = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"]
标点符号中的 i: str1 = str1.replace(i," ") #将标点所在的地方清空。 我的列表=[] myList.extend(str1.split("")) print (str1) #这是在没有标点符号的情况下打印给定的语句(在删除标点符号之后) 对于我在 myList 中: # 打印 (”____________”) 打印(我,结束='\n') 打印(“____________”)

==============接下来我会为您发布如何删除停用词============ 直到让你评论它是否有用。 谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多