【问题标题】:calculate punctuation percentage in a string in Python在 Python 中计算字符串中的标点符号百分比
【发布时间】:2018-11-14 05:35:50
【问题描述】:

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

另一方面,如果只有一个空格,我的函数会抛出一个错误

"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)

【问题讨论】:

  • 上面的代码有两个空格(text.count(" "))。我收到错误的代码是单个空格(text.count(“”))。
  • 这不是百分比的工作原理。你不减去标点字符的数量,它只是(number of punctuation characters) / (length of string),除非你的意思是减去空格,而不是标点符号。
  • 你的意思是像这样“return round((count)/(len(text) - text.count(" ")), 3)*100”?我仍然遇到同样的错误。
  • 你的错误是被零除?这意味着你传入了一些完全空格或空的字符串。
  • 这就是我无法弄清楚的。任何建议或意见将不胜感激。

标签: python percentage punctuation


【解决方案1】:

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

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)

【讨论】:

  • 请注意,OP 评论引用“上面的代码有两个空格 (text.count(" "))。我收到错误的代码是单个空格 (text.count(" ")) 。”但你说的被零除是对的。
  • @Tomothy32 我没有收到任何关于单个空格的错误。结果总是一致的。而且他为什么还要检查双空格呢?
  • 我的意思是,OP 知道他们不小心使用了多个空格的事实,他们只是没有编辑帖子。 (您的回答没有问题,如有任何混淆,请见谅。)
  • 非常感谢,现在可以用了,百分比是正确的。
  • @Vishwas 接受答案,如果它有助于将其标记为已解决,谢谢 :)
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-08
  • 2011-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多