У меня есть программа, которая:
а) считает и отображает количество токенов в каждом предложении текстового файла, введенного пользователем; б) отображает номер предложения: предложение 1, предложение 2 ...c) отображает длину в токенах каждого предложения
Проблема: я хочу также отобразить самое длинное и самое короткое предложение в файле, но моя программа не считает предложение с максимальным количеством токенов ипредложение с минимальным количеством токенов.Я не получаю сообщение об ошибке, но получаю вывод:
Самое длинное предложение этого файла содержит 1 токен
Самое короткое предложение этого файла содержит 1 токен
Средняя длина предложения этого файла: 56.55384615384615
Я пытался использовать функции max () и min () для этого.Мой код приведен ниже.
def sent_length():
while True:
try:
file_to_open =Path(input("\nYOU CHOSE OPTION 1. Please, insert your file path: "))
#opens and tokenize the sentences of the file
with open(file_to_open) 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')
sent_number=1
for t in words:
a=word_tokenize(t) #tokenize the sentence
#displays the sentence number and the sentence length
print('\n\nSentence',sent_number,'contains',len(a), 'tokens')
sent_number+=1
wordcounts = []
with open(file_to_open) as f:
text = f.read()
sentences = sent_tokenize(text)
for sentence in sentences:
words = word_tokenize(sentence)
wordcounts.append(len(words)) # appends the length of each sentence in a list
#calculates mean sentence length
average_wordcount = sum(wordcounts)/len(wordcounts)
#loop through the sentences of the file and tokenize each sentence
for x in words:
tokenized_sentences=wordpunct_tokenize(x)
longest_sen = max(tokenized_sentences, key=len) #gets the maximum number
longest_sen_len = len(longest_sen)
shortest_sen = min(tokenized_sentences, key=len) #gets the minimum number
shortest_sen_len = len(shortest_sen)
print ('\n\n The longest sentence of this file contains',longest_sen_len, 'tokens')
print ('\n\n The shortest sentence of this file contains',shortest_sen_len,'tokens')
print('\n\nThe mean sentence length of this file is: ',average_wordcount)
Мой ожидаемый результат будет выглядеть следующим образом:
eg. Самое длинное предложение этого файла содержит 70 токенов
Например, самое короткое предложение этого файласодержит 10 токенов
например. Средняя длина предложения этого файла: 56.55384615384615