如何根据条件删除字符串开头的文本?

2024-05-16 15:18:19 发布

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

假设我有以下文本:

'Reuters - Life is beautiful.'
'agency.com - China\'s currency remains pegged to the dollar and the US currency\'s sharp falls in recent months have therefore made - Chinese export prices highly competitive.'
'AP - The number of days that beaches closed or posted warnings because of pollution rose sharply in 2003 due to more rainfall, increased monitoring and tougher -standards, an environmental group said on Thursday.'
'CNN - Warming water temperatures - in the central equatorial Pacific last month may indicate the start of a new El Nino.'

我只想删除"-"前面文本开头的所有文本,并且只想删除"-"后面有空格的文本

我想要一些像:

if line.startswith(code_to_match_my_condition):
      strip_matched_text_from_line

因此,结果将是:

'Life is beautiful.'
'China\'s currency remains pegged to the dollar and the US currency\'s sharp falls in recent months have therefore made - Chinese export prices highly competitive.'
'The number of days that beaches closed or posted warnings because of pollution rose sharply in 2003 due to more rainfall, increased monitoring and tougher -standards, an environmental group said on Thursday.'
'Warming water temperatures - in the central equatorial Pacific last month may indicate the start of a new El Nino.'

我真的不知道该怎么编码。如果能在这方面得到任何帮助,我将不胜感激

事先非常感谢


Tags: andofthetoin文本iscurrency
2条回答

您可能需要使用正则表达式,例如

^[^-]+-\s+

并将其替换为空字符串,请参见a demo on regex101.com


Python中,这可能是:

import re

strings = ['Reuters - Life is beautiful.',
           'agency.com - China\'s currency remains pegged to the dollar and the US currency\'s sharp falls in recent months have therefore made - Chinese export prices highly competitive.',
           'AP - The number of days that beaches closed or posted warnings because of pollution rose sharply in 2003 due to more rainfall, increased monitoring and tougher -standards, an environmental group said on Thursday.',
           'CNN - Warming water temperatures - in the central equatorial Pacific last month may indicate the start of a new El Nino.']

rx = re.compile(r'^[^-]+-\s+')

strings = list(map(lambda string: rx.sub("", string), strings))
print(strings)

和产量

['Life is beautiful.', "China's currency remains pegged to the dollar and the US currency's sharp falls in recent months have therefore made - Chinese export prices highly competitive.", 'The number of days that beaches closed or posted warnings because of pollution rose sharply in 2003 due to more rainfall, increased monitoring and tougher -standards, an environmental group said on Thursday.', 'Warming water temperatures - in the central equatorial Pacific last month may indicate the start of a new El Nino.']

用于搜索和删除块的简单易读代码:

if " - " in line:
    index = line.find(" - ")
    line = line[index+3:]

相关问题 更多 >