簡體   English   中英

Python:寫作 function:如何計算任何文本中的平均句子長度

[英]Python: writing function: how to count average sentence length in any text

我的任務是計算文本中的平均句子長度(有很多句子)。 我嘗試了兩種方法,第一種方法是計算單詞中的標記,但在這里我不知道如何告訴程序,我想要句子中的單詞計數,而不是標記。

def satzlänge(text):
    sentences = sent_tokenize(text)
    total = 0
    count = 0
    for x in sentences:
        length = len(x)
        total += length
        count +=1
    avg_length = total / count
    print(total)
    print(count)
    return(avg_length)

print(satzlänge('Hello, this is John. How are you? How is your mother?'))

第二個我試圖用單詞標記句子,但是在這里我得到了單獨的單詞列表,我不能將 len(words) 和 sum 加在一起來得到我需要的結果。 錯誤信息:TypeError: 'int' object is not iterable

def satzlänge(text):
    sentences = sent_tokenize(text)
    for x in sentences:
        tokenizer = RegexpTokenizer(r'\w+')
        words = tokenizer.tokenize(x)
        print(words)
        print(len(words))
    avg = sum(len(words))/len(sentences)
    return(avg)

print(satzlänge('Hello, this is John. How are you? How is your mother?'))

如果你有句子並且你想得到句子中你可以使用的單詞數

length = len(sentence.split())

暫無
暫無

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

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