【问题标题】:Multiple matches with re in Python在 Python 中与 re 进行多次匹配
【发布时间】:2020-07-28 13:21:37
【问题描述】:

我正在开发一个程序,我需要帮助来匹配列表中的现有单词。 我要做的是找到列表中单词前面的数字。但是列表有多个单词。程序应该尝试这些单词,直到找到数字。我已经尝试过了,但没有帮助我。请帮忙。

代码:

import re
time = ['o\'clock', 'o clock']

# If str == 'reminder at 17 o'clock
# Program finds 17
# But if str equals this:

str = 'reminder at 17 o clock'
for a in time:
    gettime = re.findall(fr'(\b\d+\b) {a}', str)
    gettime ''.join(gettime)
    gettime = int(gettime)

print(gettime)

代码给出错误,即Invalid literal for int() with base 10: ''

如何为这两个词运行这个程序。 o'clock 和 o clock

【问题讨论】:

  • 我不确定,但这可能是因为您使用了危险的变量名称,例如 str(这是一个内置函数)和 time(这是一个有用的内置函数)在模块中,即使您可能没有导入它,仍然不是一个好主意)
  • 这只是一个例子,不是我的真实代码。我知道它们是内置函数。我急忙写下了那个名字。
  • 没关系——但以后你应该复制/粘贴功能代码

标签: python string list word python-re


【解决方案1】:

此示例可能会给出您期望的结果:

import re
time = ['o\'clock', 'o clock']

# If str == 'reminder at 17 o'clock
# Program finds 17
# But if str equals this:

str = "reminder at 17 o'clock or 18 o clock"
times = []
for a in time:
    result = re.findall(fr'(\b\d+\b) {a}', str)
    #print(result)
    for i in result:
        itime = int(i)
        times.append(itime)

print(times)

这应该显示:

[17, 18]

【讨论】:

  • 非常感谢。它真的很有效!如果您有兴趣制作 AI 语音助手,我正在开发它。我问这个问题是因为我正在为助手开发提醒应用程序。如果您想以志愿者身份加入,请在 Instagram 上私信我。 id:@ugurokuduro
猜你喜欢
  • 1970-01-01
  • 2010-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-09
  • 2017-10-04
  • 2016-01-06
  • 1970-01-01
相关资源
最近更新 更多