如果存在表达式,则从字符串中删除它们

2024-09-30 18:16:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个问题。我有这样一根线: “你能把灯关了吗?”。现在我想把这句话分成这样:

['can', 'you', 'please', 'turn', 'off', 'the', 'lights?']

但是现在我还想删除末尾的?。我知道我可以直接使用substr,但是表达式并不总是可用的。我怎样才能发现它们,如果它们存在的话,从句子中删除它们

下面是我的代码:

given_command = "Can you please turn off the lights?"

data = given_command.lower().split(" ")
print(data)

Tags: theyoudata表达式cangivencommandturn
3条回答

试试replace

In [98]: given_command = "Can you please turn off the lights?"
    ...:
    ...: data = given_command.lower().replace('?','').split(" ")
    ...:
    ...: print(data)
['can', 'you', 'please', 'turn', 'off', 'the', 'lights']

您可以使用^{}(regex)模块:

import re
given_command = r"Can you please turn off the lights?"
data = given_command.lower().split(" ")
print(list(map(lambda x: re.sub('\\W', '', x), data))) # replace any non alphanumeric character with the empty string

输出:

['can', 'you', 'please', 'turn', 'off', 'the', 'lights']

如果只有一个符号要删除(?),请使用^{}

...
>>> data = given_command.lower().replace('?', '').split(' ')
>>> print(data)
['can', 'you', 'please', 'turn', 'off', 'the', 'lights']

如果您有更多的符号,请使用^{}(我使用的是符号?!,.):

...
>>> import re
>>> data = re.sub(r'[?!,.]', '', given_command.lower()).split(' ')
>>> print(data)
['can', 'you', 'please', 'turn', 'off', 'the', 'lights']

相关问题 更多 >