Как рассчитать количество символов в предложении текстового файла? - PullRequest
0 голосов
/ 09 июля 2019

Я хочу разбить текст на предложения, а затем распечатать количество символов в каждом предложении, но программа не рассчитывает количество символов в каждом предложении.

Я попытался разбить введенный пользователем файл на предложения и выполнить цикл подсчета предложений и распечатать количество символов в каждом из них. Код, который я пробовал:

from collections import defaultdict
import nltk
from nltk.tokenize import word_tokenize
from nltk.tokenize import sent_tokenize,wordpunct_tokenize
import re
import os
import sys
from pathlib import Path

while True:
    try:
        file_to_open =Path(input("\nYOU SELECTED OPTION 8: 
            CALCULATE SENTENCE LENGTH. Please, insert your file 
path: "))
        with open(file_to_open,'r', encoding="utf-8") as f:
            words = sent_tokenize(f.read())
            break
    except FileNotFoundError:
        print("\nFile not found. Better try again")
    except IsADirectoryError:
        print("\nIncorrect Directory path.Try again")


print('\n\n This file contains',len(words),'sentences in total')



wordcounts = []
caracter_count=0
sent_number=1
with open(file_to_open) as f:
    text = f.read()
    sentences = sent_tokenize(text)
    for sentence in sentences:
        if sentence.isspace() !=True:
            caracter_count = caracter_count + 1
            print("Sentence", sent_number,'contains',caracter_count, 
'characters')
            sent_number +=1
            caracter_count = caracter_count + 1

ХОЧУ ПЕЧАТЬ ЧТО-ТО, КАК:

"SENTENCE 1 HAS 35 CHARACTERS" "SENTENCE 2 HAS 45 CHARACTERS"

и тд ....

Вывод, который я получаю с этой программой: Этот файл содержит всего 4 предложения «Предложение 1 содержит 0 символов» «Предложение 2 содержит 1 символов» «Предложение 3 содержит 2 символа» «Предложение 4 содержит 3 символа»

Кто-нибудь может помочь мне сделать это?

Ответы [ 2 ]

0 голосов
/ 09 июля 2019

Ну, ваш вопрос кажется интересным, эта проблема имеет простое решение. Помните, что для первого запуска используйте эту команду "nltk.download ('punkt')", после первого запуска просто закомментируйте ее.

import nltk
#nltk.download('punkt')
from nltk.tokenize import sent_tokenize

def count_lines(file):
    count=0
    myfile=open(file,"r")
    string = ""

    for line in myfile:
        string+=line  
        print(string)

    number_of_sentences = sent_tokenize(string)

    for w in number_of_sentences:
        count+=1
        print("Sentence ",count,"has ",len(w),"words")

count_lines("D:\Atharva\demo.txt")

ВЫХОД:

What is Python language?Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library. The best way we learn anything is by practice and exercise questions. We  have started this section for those (beginner to intermediate) who are familiar with Python.  
Sentence  1 has  119 words
Sentence  2 has  175 words
Sentence  3 has  134 words
Sentence  4 has  117 words
Sentence  5 has  69 words
Sentence  6 has  95 words
0 голосов
/ 09 июля 2019

Вы не учитываете количество символов в предложении с помощью caracter_count.Я думаю, что изменение вашего цикла for на:

sentence_number = 1
for sentence in sentences:
    if not sentence.isspace():
        print("Sentence {} contains {} characters".format(sentence_number, len(sentence))
        sentence_number += 1

будет работать нормально

...