首页 > 解决方案 > 如何使用 RegEx 在 Python 中设置新字母表?

问题描述

我已经下载了一个 RSS 文件并保存为city.txt.

然后我必须从<lastBuildDate>标签中获取日期。

日期格式为:Fri,28 Aug 2020然后我必须使用 RegEx 翻译日期和月份。

我已经设法得到日期,但在找到日期和月份后更改日期和月份时遇到问题。

我必须使用re.sub吗?

我的代码:

import re
with open('city.txt', 'r', encoding = 'utf-8') as f:
    txt = f.read()
    tag_pattern =r'<''lastBuildDate'r'\b[^>]*>(.*?)</''lastBuildDate'r'>'
    found = re.findall(tag_pattern, txt, re.I)
    found = list(set(found))
    for f in found :print('\t\t', f)

标签: pythonregex

解决方案


我已根据您的要求更新了您的代码,请试一试。

代码

import re
import locale
import datetime
with open('city.txt', 'r', encoding = 'utf-8') as f:
    txt = f.read()
    tag_pattern =r'<''lastBuildDate'r'\b[^>]*>(.*?)</''lastBuildDate'r'>'
    found = re.findall(tag_pattern, txt, re.I)
    found = list(set(found))
    for f in found :
        locale.setlocale(locale.LC_TIME, "en")
        temp=datetime.datetime.strptime(f, '%a, %d %b %Y %H:%M:%S GMT')
        locale.setlocale(locale.LC_TIME, "el-GR")
        print(temp.strftime("%a, %d %b %Y %H:%M:%S"))

样本输入

<lastBuildDate>Fri, 28 Jan 2020 13:32:12 GMT</lastBuildDate>
<lastBuildDate>Sun, 27 Feb 2020 15:36:53 GMT</lastBuildDate>
<lastBuildDate>Mon, 26 Aug 2020 16:30:43 GMT</lastBuildDate>

输出

Ôåô, 26 Áõã 2020 16:30:43
Ðåì, 27 Öåâ 2020 15:36:53
Ôñé, 28 Éáí 2020 13:32:12

推荐阅读