簡體   English   中英

在Python中計算字符串中的標點符號百分比

[英]calculate punctuation percentage in a string in Python

我一直在努力計算句子中標點符號的百分比。 由於某種原因,我的函數在進行雙倍間距時可以工作,但會計算所有字符和空白。 例如,我有一個文本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)

在這里,進行這些小的更改,您的count_punct函數應該已啟動並正在運行。.代碼中斷的原因是,您正在檢查___而不是_ 即3個連續的空格而不是一個空格。 這就是為什么差異總是導致相同的值的原因。

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時,這是一個邏輯錯誤,因為字符串的lengthnumber of spaces都相等。 因此,差為0。

要解決此問題,您只需添加一個if語句(已在上面添加)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM