删除标点符号python

时间:2012-11-20 01:36:15

标签: python python-3.x

在您发布链接以删除标点符号的最佳方法之前。

我正在创建一个madLib游戏,用名词,副词,动词,形容词等替换段落中的单词;它应该从一个单独的文件中取一个随机单词并将其打印到适当的段落中,即动词运行将被放入段落声明VERB的位置。我唯一的问题是,当我要替换的单词旁边有标点符号时,我无法执行此操作。比如VERB,或VERB!

我的问题是如何在保持标点符号的同时替换所有这些值。

5 个答案:

答案 0 :(得分:2)

noun1="Donkey"
print("This should print a %s here"%(noun1))

基本上,您可以获取输入变量,并将其视为此示例。

答案 1 :(得分:2)

不确定您的使用案例,但replace参数设置为1的count是否有效?

>>> test = 'This is a VERB! Whoa, a VERB? Yeah, a VERB!#$%'
>>> test.replace('VERB', 'running', 1)
'This is a running! Whoa, a VERB? Yeah, a VERB!#$%'
>>> test.replace('VERB', 'running', 1).replace('VERB', 'swimming', 1).replace('VERB', 'sleeping', 1)
'This is a running! Whoa, a swimming? Yeah, a sleeping!#$%'

当然,您必须对重复次数进行一些调整,但它应该处理标点符号。

根据@ mgilson的建议,您可以通过执行以下操作删除对replace的多次调用:

In [14]: s = 'This is a VERB! Whoa, a VERB? Yeah, a VERB!#$%'

In [15]: verbs = ['running', 'jumping', 'swimming']

In [16]: reduce(lambda x, y: x.replace('VERB', y, 1), verbs, s)
Out[16]: 'This is a running! Whoa, a jumping? Yeah, a swimming!#$%'

这使用reduce函数在主字符串上运行replace,使用verbs中的值作为要替换的值。 reduce的最后一个参数是字符串本身,它将包含每次迭代的替换结果(并且在开始时将是'普通'字符串)。

答案 2 :(得分:0)

使用re模块中的子功能。捕获单词后面的字符,然后用新单词替换单词并使用反向引用附加捕获的标点符号:

>>> import re
>>> s = "VERB,"
>>> print re.sub(r'VERB([\,\!\?\;\.]?)', r'newword\1', s)
newword,

您可以展开角色类[\,\!\?\;\.]以包含您希望遇到的任何标点符号,这只是一个示例。

答案 3 :(得分:0)

子功能可以很好地解决您的问题

from re import *
contents = 'The !ADJECTIVE! panda walked to the !NOUN? and then *VERB!. A nearby <NOUN> was unaffected by these events.'
print('Enter an adjective: ', end = '')
adj = input()
print('Enter a noun: ', end = '')
noun1 = input()
print('Enter a verb: ', end = '')
verb = input()
print('Enter a noun: ', end = '')
noun2 = input()
contents = sub(r'adjective',adj,contents,count = 1, flags = IGNORECASE)
contents = sub(r'noun',noun1,contents,count = 1, flags = IGNORECASE)
contents = sub(r'verb',verb,contents,count = 1, flags = IGNORECASE)
contents = sub(r'noun',noun2,contents,count = 1, flags = IGNORECASE)

sub函数具有五个参数。 re.sub(查找表达式,要替换的字符串,完成替换的字符串,计数,即应替换的出现次数,IGNORECASE查找所有大小写,无论大小写) 代码输出

Enter an adjective: silly
Enter a noun: chandelier
Enter a verb: screamed
Enter a noun: pickup truck
The !silly! panda walked to the !NOUN? and then *VERB!. A nearby <NOUN> was
unaffected by these events.
The !silly! panda walked to the !chandelier? and then *VERB!. A nearby <NOUN> was
unaffected by these events.
The !silly! panda walked to the !chandelier? and then *screamed!. A nearby <NOUN> was
unaffected by these events.
The !silly! panda walked to the !chandelier? and then *screamed!. A nearby <pickup truck> was
unaffected by these events.

标点符号不受这些事件的影响。 希望这会有所帮助

答案 4 :(得分:0)

string.punctuation包含以下字符:

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

您可以使用translate和maketrans函数将标点符号映射为空值(替换)

import string

'This, is. A test! VERB! and VERB,'.translate(str.maketrans('', '', string.punctuation))

输出:

“这是一个测试VERB和VERB”