【问题标题】:Use regex to find and merge words in a string Python使用正则表达式在字符串 Python 中查找和合并单词
【发布时间】:2019-10-28 01:05:18
【问题描述】:

我正在尝试找到一种方法来匹配和合并来自如下字符串的团队名称。我用正则表达式尝试了几种不同的方法,但没有成功。几个例子:

'30 Detroit Red Wings 12 47:06 3 8 1 3 7 0.292'

'31 Los Angeles Kings 11 47:45 4 7 0 4 8'

24 Anaheim Ducks 12 47:49 7 5 0 7 14 0.583

我希望输出如下所示:

[30, 'Detroit Red Wings', 12, 47:06, 3, 8, 1, 3, 7, 0.292]

[24, 'Anaheim Ducks', 12, 47:49, 7, 5, 0, 7, 14, 0.583]

这是我尝试使用正则表达式但没有成功:

pattern = re.compile(r'\b\w+\b')
matches = pattern.finditer(i)

【问题讨论】:

  • split() 会很有用
  • @SPYBUG96。拆分会将每个单词放在一个单独的元素中。不会工作。我试过了
  • 哦,我明白你的意思了。团队名称中有数字吗?
  • 理论上可以使用拆分,检查列表中的每一项是否为整数,然后将可以转换为字符串的部分合并。

标签: python regex python-3.x string pattern-matching


【解决方案1】:

这是一个使用re.findall的选项:

inp = '30 Detroit Red Wings 12 47:06 3 8 1 3 7 0.292'
matches = re.findall(r'\d+:\d+|\d+(?:\.\d+)?|[A-Za-z]+(?: [A-Za-z]+)*', inp)
print(matches)

打印出来:

['30', 'Detroit Red Wings', '12', '47:06', '3', '8', '1', '3', '7', '0.292']

使用的正则表达式模式匹配时间字符串、整数/浮点数或一系列仅包含字母的单词:

\d+:\d+                    match a time string (e.g. '47:06')
|                          or
\d+(?:\.\d+)?              match an integer/floating point number
|                          or
[A-Za-z]+(?: [A-Za-z]+)*   match a series of words (e.g. Detroit Red Wings)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2020-08-27
    • 1970-01-01
    • 2019-02-20
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多