Как вынести пунктуацию из строки и найти количество слов определенной длины? - PullRequest
0 голосов
/ 06 мая 2019

Я пытаюсь создать функцию, которая открывает файл .txt и считает слова, длина которых равна числу, указанному пользователем.
Файл .txt:

This is a random text document. How many words have a length of one? 
How many words have the length three?  We have the power to figure it out! 
Is a function capable of doing this?

Я могу открыть и прочитать файл, но не могу исключить пунктуацию и найти длину каждого слова.

def samplePractice(number):
    fin = open('sample.txt', 'r')
    lstLines = fin.readlines()
    fin.close

    count = 0

    for words in lstLines:
        words = words.split()

    for i in words:
        if len(i) == number:
            count += 1
    return count

Ответы [ 3 ]

0 голосов
/ 06 мая 2019

Я написал пример кода для удаления знаков препинания и для подсчета количества слов.Изменить в соответствии с вашими требованиями.

    import re
    fin = """This is a random text document. How many words have a length of one? How many words have the length three?  We have the power to figure it out! Is a function capable of doing this?"""
    fin = re.sub(r'[^\w\s]','',fin)
    print(len(fin.split()))

Приведенный выше код печатает количество слов.Надеюсь, это поможет !!

0 голосов
/ 06 мая 2019

вместо каскадирования replace() просто используйте strip() одноразовый вызов

Редактировать: более чистая версия

pl = '?!."\'' # punctuation list

def samplePractice(number):
    with open('sample.txt', 'r') as fin:
        words = fin.read().split()

    # clean words
    words = [w.strip(pl) for w in words]

    count = 0
    for word in words:
        if len(word) == number:
            print(word, end=', ')
            count += 1

    return count

result = samplePractice(4)
print('\nResult:', result)

выход: * +1010 *

This, text, many, have, many, have, have, this, 
Result: 8

ваш код почти в порядке, это просто второй блок для неправильной позиции

pl = '?!."\'' # punctuation list

def samplePractice(number):
    fin = open('sample.txt', 'r')
    lstLines = fin.readlines()
    fin.close

    count = 0

    for words in lstLines:
        words = words.split()

        for i in words:
            i = i.strip(pl)  # clean the word by strip
            if len(i) == number:
                count += 1
    return count

result = samplePractice(4)
print(result)

выход:

8
0 голосов
/ 06 мая 2019

Вы можете попробовать использовать replace () в строке и передать нужную пунктуацию и заменить ее пустой строкой ("").

Это будет выглядеть примерно так:

puncstr = "Hello!"

nopuncstr = puncstr.replace(".", "").replace("?", "").replace("!", "")
...