2

我想替换两个或多个以大写字符开头的连续单词并用它们的缩写替换它们,我设法找到了单词

def find(name):
        return re.findall('([A-Z][a-z]+(?=\s[A-Z])(?:\s[A-Z][a-z]+)+)', name)

但是当我尝试替换单词时,我无法做到

这是我得到的

import re


def main():
    name = raw_input(" Enter name: ")

    print find(name)


def find(name):
    return re.sub(r'([A-Z][a-z]+(?=\s[A-Z])(?:\s[A-Z][a-z]+)+)', replacement, name)


def replacement(match):
    return match.group[0].upper()

main()

例如

输入:我参加了年度股东大会。输出:我参加了年度股东大会。

感谢任何帮助

4

2 回答 2

1

如果您replacement按如下方式修改您的函数,您的示例应该可以正常工作:

def replacement(match):
    return ''.join(y[0] for y in m.group(0).split())
于 2013-05-23T20:13:06.043 回答
1

描述

在这里,我使用了两个单独的表达式,第一个提取所有标题大小写的单词,其中单词连续包含 2 个或更多单词。第二个表达式提取每个单词的第一个字母......使用逻辑将它们缝合在一起以替换源字符串中的值。

(?:^|\s+)((?:\s*\b[A-Z]\w{1,}\b){2,})

在此处输入图像描述

\b([A-Z])

在此处输入图像描述

例子

$Regex = '(?:^|\s+)((?:\s*\b[A-Z]\w{1,}\b){2,})'
$String = 'I went to the Annual General Meeting with some guy named Scott Jones on Perl Compatible Regular Expressions. '

Write-Host start with 
write-host $String
Write-Host
Write-Host found
$Matches = @()
([regex]"$Regex").matches($String) | foreach {
    $FoundThis = $_.Groups[1].Value
    write-host "group one $($_.Groups[1].Index) = '$($FoundThis)'"

    [string]$Acronym = ""
    ([regex]"\b([A-Z])").matches($FoundThis) | foreach {
        $Acronym += $_.Groups[1].Value
        } # next match

    $String = $String -replace $FoundThis, $Acronym
    } # next match


Write-Host $String

产量

start with
I went to the Annual General Meeting with some guy named Scott Jones on Perl Compatible Regular Expressions. 

found
group one 14 = 'Annual General Meeting'
group one 57 = 'Scott Jones'
group one 72 = 'Perl Compatible Regular Expressions'
I went to the AGM with some guy named SJ on PCRE. 

免责声明

  • 是的,我知道 OP 要求提供 python 示例,但我更熟悉 powershell。逻辑是一样的。
  • 如前所述,这将匹配专有名称,并且如果句子的第一个单词恰好是标题大小写,然后是标题大小写的第二个单词。所以你需要自己做错误检查
于 2013-05-23T19:57:55.263 回答