Python从每个单词的第一个字符创建首字母缩略词并包含数字

问题描述 投票:3回答:4

我有一个字符串如下: theatre = 'Regal Crown Center Stadium 14'

我想把它打成一个基于每个单词中第一个字母的首字母缩略词,但也包括两个数字: 期望的输出= 'RCCS14'

我的代码尝试如下: acronym = "".join(word[0] for word in theatre.lower().split()) acronym = "".join(word[0].lower() for word in re.findall("(\w+)", theatre)) acronym = "".join(word[0].lower() for word in re.findall("(\w+ | \d{1,2})", theatre)) acronym = re.search(r"\b(\w+ | \d{1,2})", theatre)

在其中我结束了类似:rccs1,但似乎无法捕获最后一个数字。可能存在这个数字位于名称中间的情况:'Regal Crown Center 14 Stadium'。 TIA!

python regex elements capture
4个回答
2
投票

See regex in use here

(?:(?<=\s)|^)(?:[a-z]|\d+)
  • (?:(?<=\s)|^)确保前面的空格或行的开头
  • (?:[a-z]|\d+)匹配一个字母或一个或多个数字

i标志(python中的re.I)允许[a-z]匹配其大写变体。

See code in use here

import re

r = re.compile(r"(?:(?<=\s)|^)(?:[a-z]|\d+)", re.I)
s = 'Regal Crown Center Stadium 14'

print(''.join(r.findall(s)))

上面的代码查找正则表达式匹配的所有实例,并将列表项连接到单个字符串中。

结果:RCCS14


1
投票

您可以使用re.sub()删除所有小写字母和空格。

正则表达式:[a-z ]+

细节:

  • []+在一次和无限次之间匹配列表中的单个字符

Python代码:

re.sub(r'[a-z ]+', '', theatre)

输出:RCCS14

Code demo


0
投票

我不能评论,因为我没有足够的声誉,但S. Jovan的回答并不令人满意,因为它假设每个单词都以大写字母开头,并且每个单词都有一个且只有一个大写字母。

re.sub(r'[a-z ]+', '', "Regal Crown Center Stadium YB FIEUBFB DBUUFG FUEH  14")

将返回'RCCSYBFIEUBFBDBUUFGFUEH14'

但是,在这种情况下,ctwheels答案将能够起作用:

r = re.compile(r"\b(?:[a-z]|\d+)", re.I)
s = 'Regal Crown Center Stadium YB FIEUBFB DBUUFG FUEH  14'

print(''.join(r.findall(s)))

将打印

RCCSYFDF14

0
投票
import re
theatre = 'Regal Crown Center Stadium 14'
r = re.findall("\s(\d+|\S)", ' '+theatre)
print(''.join(r))

给我RCCS14

© www.soinside.com 2019 - 2024. All rights reserved.