python - 在Python中分割多字标签的有效方法

标签 python regex

给定一个类似的文本

这是一个#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/

相关文章:

python - 扭曲的 adbapi 关闭自动提交(psycopg2)

用于连接的 Python 正则表达式替代方案

c++ - 如何直接从Google Map批量下载大量高分辨率卫星图片?

javascript - AngularJS ng-pattern 的正则表达式问题

java - 在 Java 中从文本文件中检索单个特定数字的有效方法

javascript - JS RegExp 捕获括号

java - 在正则表达式中设置最小和最大字符

python - 如何从选择中获取边缘索引?

python - 将 matplotlib 矩形边缘设置为指定宽度之外?

java 正则表达式转义序列