给定一个类似的文本
这是一个#hashtag,这是一个#multiWordHashtag
我需要输出
这是一个主题标签,这是一个多字主题标签
目前,我使用这个函数:
def do_process_eng_hashtag(input_text: str):
result = []
for word in input_text.split():
if word.startswith('#') and len(word) > 1:
word = list(word)
word[1] = word[1].upper()
word = ''.join(word)
word = ' '.join(re.findall('[A-Z][^A-Z]*', word))
result.append(word)
return ' '.join(result)
但我想知道是否有更有效、更简洁的方法来做到这一点?
最佳答案
使用re.sub
:
您可以指定替换函数:
def do_process_eng_hashtag(input_text: str) -> str:
return re.sub(
r'#[a-z]\S*',
lambda m: ' '.join(re.findall('[A-Z][^A-Z]*|[a-z][^A-Z]*', m.group().lstrip('#'))),
input_text,
)
替换函数(lambda)会将哈希标签拆分为多个单词:
>>> re.findall('[A-Z][^A-Z]*|[a-z][^A-Z]*', '#multiWordHashtag'.lstrip('#'))
['multi', 'Word', 'Hashtag']
>>> do_process_eng_hashtag('THIS is a #hashtag and this is a #multiWordHashtag')
'THIS is a hashtag and this is a multi Word Hashtag '
关于python - 在Python中分割多字标签的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68448243/