删除 python 中的所有标点符号
Removing all punctuation marks in python
作为更大程序的一部分,我需要删除字符串中的所有标点符号。
当我像这样为每个标记分别写它时它正在工作:
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
你能告诉我,我做错了什么吗?
你的问题是
if punc in words:
这会检查列表中是否有一个元素是 punc
,而不是列表中的任何元素是否包含 punc
。去掉那条线,它应该可以工作。
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
作为更大程序的一部分,我需要删除字符串中的所有标点符号。 当我像这样为每个标记分别写它时它正在工作:
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
你能告诉我,我做错了什么吗?
你的问题是
if punc in words:
这会检查列表中是否有一个元素是 punc
,而不是列表中的任何元素是否包含 punc
。去掉那条线,它应该可以工作。
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