Skip to main content
 首页 » 编程设计

python之使用正则表达式在月份名称之前拆分字符串

2024年10月25日27mate10pro

我有一堆带有随机文本的行,每行的末尾都有一个时间戳。我试图在时间戳之前拆分这些行。

当前输出:

Yes, I'd say so. Nov 08, 2014 UTC 
Hell yes! Oct 01, 2014 UTC  
Anbefalt som bare det, løp og kjøp. Sep 16, 2014 UTC 
Etc. 

所需的输出(“制表符”是指实际的空白):

Yes, I'd say so. <tab> Nov 08, 2014 UTC 
Hell yes! <tab> Oct 01, 2014 UTC 
Anbefalt som bare det, løp og kjøp. <tab> Sep 16, 2014 UTC 
Etc. 

到目前为止,我已经使用“替换”在月份之前放置制表符。像这样:

my_string.replace("May ", "\tMay ").replace("Apr ", "\tApr ").replace("Mar ", "\tMar ").replace("Feb ", "\tFeb ") etc. (incomplete code) 

这工作得很好,除非随机文本涉及月份的名称,例如“我去年五月买的,很棒的东西”。由于日期是以这种特定方式格式化的,如果可能的话,我想用正则表达式和通配符对此进行改进。有没有办法在这些日期之前放置一个标签?正如您在上面看到的,日期格式如下:

[Three-letter abbreviation of the month] [two-digit day] [,] [four-digit year] [UTC] 

例如

Oct 31, 2014 UTC 

请原谅业余代码和方法,我是绝对的正则表达式 n00b。我在这里四处寻找答案,但我做空了。我希望有人能提供帮助!

请您参考如下方法:

如果你总能保证它有那么多单词,那么你就不需要正则表达式,只需使用内置函数反向拆分和连接,例如:

s = "Yes, I'd say so. Nov 08, 2014 UTC" 
split = s.rsplit(None, 4) 
new = split[0] + '\t' + ' '.join(split[1:]) 
# "Yes, I'd say so.\tNov 08, 2014 UTC"