Поиск самого длинного слова в файле .txt без знаков препинания - PullRequest
1 голос
/ 30 мая 2020

Я выполняю Python упражнений на ввод-вывод файлов и, хотя я добился огромного прогресса в упражнении, в котором я пытаюсь найти самые длинные слова в каждой строке файла .txt, я не могу избавиться от знаки препинания .

Вот код, который у меня есть:

with open("original-3.txt", 'r') as file1:
lines = file1.readlines()
for line in lines:
    if not line == "\n":
        print(max(line.split(), key=len))

Это результат, который я получаю

Это это файл original-3.txt, в котором я читаю данные из

'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.

"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"

He took his vorpal sword in hand:
Long time the manxome foe he sought,
So rested he by the Tumtum tree,
And stood a while in thought.

And, as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!

One two! One two! And through and through
The vorpal blade went snicker-snack!
He left it dead, and with its head
He went galumphing back.

"And hast thou slain the Jabberwock?
Come to my arms, my beamish boy!"
"Oh frabjous day! Callooh! Callay!"
He chortled in his joy.

'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.

Как видите, я получаю знаки препинания, например ["," ";" "?" "!"]

Как вы думаете, я могу только получить сами слова?

Спасибо

Ответы [ 3 ]

2 голосов
/ 30 мая 2020

Используя Regex, очень легко получить length of longest word:

import re

for line in lines:
    found_strings = re.findall(r'\w+', line)
    print(max([len(txt) for txt in found_strings]))
1 голос
/ 30 мая 2020

Это решение не использует регулярные выражения. Он разбивает строку на слова, а затем очищает каждое слово, чтобы оно содержало только буквы алфавита.

with open("original-3.txt", 'r') as file1:
    lines = file1.readlines()
    for line in lines:
        if not line == "\n":
            words = line.split()
            for i, word in enumerate(words):
                words[i] = "".join([letter for letter in word if letter.isalpha()])
            print(max(words, key=len))
1 голос
/ 30 мая 2020

Вам необходимо strip эти символы из слов:

with open("original-3.txt", 'r') as file1:
    lines = file1.readlines()
for line in lines:
    if not line == "\n":
        print(max(word.strip(",?;!\"") for word in line.split()), key=len))

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

import re


for line in lines: 
    words = re.findall(r"\w+", line) 
    if words: 
        print(max(words, key=len)) 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...