在Python中,将句子中的某些数字(如日期、时间、电话号码)从数字转换为单词

2024-04-20 09:18:38 发布

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

我对Python有点陌生,所以我为自己的不足道歉。我在python中有一段代码,在其他用户的帮助下得到了完善(谢谢),它使用字典将日期从数字转换为单词,例如3.6.2015=>;三月三二日一千五使用: 日期=原始输入(“给出日期:”) 我想输入一个句子,例如:“今天是3.6.2015,现在是10:00,天在下雨”,从中我不知道如何在句子中搜索日期、时间或电话号码,并将转换应用到该日期和时间。 如果有人能帮忙,谢谢。你知道吗


Tags: 代码用户gt字典时间电话号码数字单词
1条回答
网友
1楼 · 发布于 2024-04-20 09:18:38

可以使用正则表达式:

import re

s = "today is 3.6.2015, it is 10:00 o'clock and it's rainy"

mat = re.search(r'(\d{1,2}\.\d{1,2}\.\d{4})', s)
date = mat.group(1)

print date  # 3.6.2015

注意,如果输入文本中没有与此正则表达式匹配的内容,则会引发一个AttributeError,您必须阻止它(例如if mat:)或处理它。你知道吗

编辑

假设可以将转换代码转换为函数,则可以使用re.sub

import re

def your_function(num_string):
    # Whatever your function does
    words_string = "march.third.two thousand fifteen"
    return words_string

s = "today is 3.6.2015, it is 10:00 o'clock and it's rainy"

date = re.sub(r'(\d{1,2}\.\d{1,2}\.\d{4})', your_function, s)

print date 
# today is march.third.two thousand fifteen, it is 10:00 o'clock and it's rainy

只需修改your_function,将3.6.2015更改为march.third.two thousand fifteen。你知道吗

相关问题 更多 >