【问题标题】:Counting three letter acronyms in a line with Regex Python [closed]用 Regex Python 计算一行中的三个字母首字母缩写词[关闭]
【发布时间】:2013-08-17 11:02:09
【问题描述】:

我需要用 python 编写一个程序来查看给定的文件。假设 acronyms.txt,然后返回多少行包含至少 1 个三字母缩写词的百分比值。 例如:

NSW is a very large state.
It's bigger than TAS.
but WA is the biggest!

阅读后它应该返回 66.7%,因为 66.7% 的行包含三个字母的首字母缩写词。如您所见,它也四舍五入到小数点后一位。我对正则表达式不是很熟悉,但我认为正则表达式最简单。

编辑:

我已经完成了代码,但我需要它来识别它们之间带有点的首字母缩略词,EG N.S.W 应该被识别为首字母缩略词。我该怎么做?

任何帮助将不胜感激!

【问题讨论】:

    标签: python regex python-3.x acronym


    【解决方案1】:

    你可以这样做:

    import re
    cnt = 0
    with open('acronyms.txt') as myfile:
        lines = myfile.readlines()
        length = len(lines)
        for line in lines:
            if re.search(r'\b[A-Z]{3}\b', line) is not None:
                cnt += 1
    
    print("{:.1f}%".format(cnt/length*100))
    

    r'[A-Z]{3}' 连续匹配三个(并且只有三个)大写字母。如果找到一个搜索,那么我们添加一个计数。

    然后我们只需将计数除以行的长度,并按照您的显示打印结果。

    【讨论】:

    • 这也将匹配 4、5 等首字母缩写词。
    【解决方案2】:

    你可以这样做:

    total_lines = 0
    matched_lines = 0
    for line in open("filename"):
        total_lines += 1
        matched_lines += bool(re.search(r"\b[A-Z]{3}\b", line))
    print "%f%%" % (float(matched_lines) / total_lines * 100)
    

    注意搜索模式中的“\b”——它匹配单词开头或结尾的空字符串。它可以帮助您防止与超过 3 的首字母缩略词('asdf ASDF asdf')或单词中的首字母缩略词('asdfASDasdf')匹配。

    【讨论】:

    • 我喜欢上面的,但我如何让它包含标点符号?因为我需要它来匹配 N.S.W 作为首字母缩略词。我该怎么做?
    • @user2655778,使用其他正则表达式。类似 r"\b([A-Z]\.){3}".
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多