计算 Python 中字符串中的标点符号百分比

calculate punctuation percentage in a string in Python

我一直在计算句子中标点符号的百分比。出于某种原因,我的函数在双倍间距时有效,但计算所有字符和白色 space。例如,我有一个文本 DEACTIVATE: OK,所以当我减去标点符号时总长度为 14,则长度为 13,因此百分比应该为 1/13 = 7.63%,但是,我的函数给出 7.14%,这基本上是1/14 = 7.14%

另一方面,如果只有一个白色 space,我的函数会抛出错误

"ZeroDivisionError: division by zero".

这是我的代码供您参考和一个简单的文本示例

text= "Centre to position, remaining shift is still larger than maximum (retry nbr=1, centring_stroke.r=2.7662e-05, max centring stroke.r=2.5e-05)"
text2= "DEACTIVATE: KU-1421"

导入字符串

def count_punct(text):
    count = sum([1 for char in text if char in string.punctuation])
    return round(count/(len(text) - text.count("  ")), 3)*100
df_sub['punct%'] = df_sub['Err_Text2'].apply(lambda x: count_punct(x))
df_sub.head(20)

在这里,进行这些小的更改,您的 count_punct 函数应该启动并且 运行.. 您的代码被破坏的原因是因为您正在检查 ___ 而不是 _。即 3 个连续的 spaces 而不是一个 space。这就是为什么差异总是导致相同的值。

import string
def count_punct(text):
    if text.strip() == "": # To take of care of all space input
        return 0
    count = sum([1 if char in string.punctuation else 0 for char in text ])
    spaces = text.count(" ") # Your error is here, Only check for 1 space instead of 3 spaces
    total_chars = len(text) - spaces

    return round(count / total_chars, 3)*100

text= "DEACTIVATE: OK"

print(count_punct(text))

输出:

7.7

以及零除错误。当total_chars为0时是逻辑错误,因为string的lengthnumber of spaces是相等的。因此差异为 0.

要解决此问题,您只需添加一个 if 语句(已在上面添加)

if text.strip() == "":
    print(0)