如何在文本中找到所有初始化?

时间:2009-08-08 10:34:45

标签: full-text-search

我必须在纯文本文件中找到所有初始化(有字母的单词,如SAP,JSON或XML)。有没有现成的脚本? Ruby,Python,Perl - 语言并不重要。到目前为止,我什么都没找到。

此致

的Stefan

4 个答案:

答案 0 :(得分:20)

你走了:

perl -e 'for (<>) { for (m/\b([[:upper:]]{2,})\b/) { print "$1\n"; } }' textinput.txt

抓住所有至少两个字符长的全大写单词。我使用[[:upper:]]代替[A-Z],以便它适用于任何语言环境。

答案 1 :(得分:4)

更简单的Conspicuous Compiler's answer版本使用-p标志来删除所有丑陋的循环代码:

perl -p -e 'm/\b([[:upper:]]{2,})\b/' input.txt

答案 2 :(得分:2)

/[A-Z]{2,}/之类的正则表达式应该可以解决问题。

答案 3 :(得分:0)

这是一个允许数字的Python 2.x解决方案(参见示例)。 更新:代码现在适用于Python 3.1,3.0和2.1到2.6(含)。

dos-prompt>type find_acronyms.py
import re

try:
    set
except NameError: 
    try:
        from sets import Set as set # Python 2.3
    except ImportError: 
        class set: # Python 2.2 and earlier
            # VERY minimal implementation
            def __init__(self):
                self.d = {}
            def add(self, element):
                self.d[element] = None
            def __str__(self):
                return 'set(%s)' % self.d.keys()

word_regex = re.compile(r"\w{2,}", re.LOCALE)
# min length is 2 characters

def accumulate_acronyms(a_set, an_iterable):
    # updates a_set in situ
    for line in an_iterable:
        for word in word_regex.findall(line):
            if word.isupper() and "_" not in word:
                a_set.add(word)

test_data = """
A BB CCC _DD EE_ a bb ccc k9 K9 A1
It's a CHARLIE FOXTROT, said MAJ Major Major USAAF RETD.
FBI CIA MI5 MI6 SDECE OGPU NKVD KGB FSB
BB CCC # duplicates
_ABC_DEF_GHI_ 123 666 # no acronyms here
"""

result = set()
accumulate_acronyms(result, test_data.splitlines())
print(result)


dos-prompt>\python26\python find_acronyms.py
set(['CIA', 'OGPU', 'BB', 'RETD', 'CHARLIE', 'FSB',
'NKVD', 'A1', 'SDECE', 'KGB', 'MI6', 'USAAF', 'K9', 'MAJ',
'MI5', 'FBI', 'CCC', 'FOXTROT'])
# Above output has had newlines inserted for ease of reading.
# Output from 3.0 & 3.1 differs slightly in presentation.
# Output from 2.1 differs in item order.