删除python

时间:2017-05-12 07:45:45

标签: python python-2.7 text-mining text-analysis

我需要删除字符串中的所有标点符号,作为更大程序的一部分。 当我为每个标记编写serepatly时它正在工作:

words = [word.replace(".", "") for word in words]

但是当我尝试在循环中执行它时,它无法正常工作。

line = "I was going to leave her, but in the very last moment I had changed 
my mind. Interesting thing, many nice ways to use."
words = line.lower().split()
for punc in [".",","]:
    if punc in words:
        words = [word.replace(punc, "") for word in words]
print words

你能告诉我,我做错了吗?

2 个答案:

答案 0 :(得分:4)

translate适合您:

>>line = '''I was going to leave her, but in the very last moment I had changed 
my mind. Interesting thing, many nice ways to use.'''
>>line = line.translate(None, ',.')
I was going to leave her but in the very last moment I had changed 
my mind Interesting thing many nice ways to use

答案 1 :(得分:1)

你的问题是

if punc in words:

这将检查列表中的一个元素是punc,而不是列表中的任何元素是否包含punc。只是摆脱那条线,它应该工作。