2

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

我正在创建一个 madLib 游戏,用名词、副词、动词、形容词等替换段落中的单词;它应该从一个单独的文件中取出一个随机单词并将其打印到适当的段落中,即动词 running 将被放置在段落状态 VERB 的位置。我遇到的唯一问题是,当我要替换的单词旁边有标点符号时,我无法做到这一点。比如VERB,或者VERB!

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

4

5 回答 5

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

本质上,您可以获取输入变量,并像此示例一样对待它们。

于 2012-11-20T01:38:33.680 回答
2

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

>>> 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 的最后一个参数是字符串本身,它将包含每次迭代的替换结果(并且一开始将是“正常”字符串)。

于 2012-11-20T01:44:01.177 回答
0

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

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

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

于 2012-11-20T02:01:35.893 回答
0

string.punctuation包含以下字符:

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

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

import string

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

输出:

'这是一个测试动词和动词'

于 2020-03-17T15:20:46.820 回答
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(要查找的表达式,要替换的字符串,进行替换的字符串,count ie,应该替换的出现次数,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.

标点符号不受这些事件的影响。希望这可以帮助

于 2018-07-07T04:47:19.187 回答