Почему этот код string.punctuation не работает для удаления пунктуации? - PullRequest
1 голос
/ 11 февраля 2020

Я запутался, почему этот код не работает так, как я хочу. Я читаю в текстовом файле и печатаю каждый элемент (через запятую) в новую строку. Каждый элемент окружен "" и также содержит знаки препинания. Я пытаюсь убрать эту пунктуацию. Я знаком с string.punctuation и у меня он работает в тесте в моем примере, но он не работает с элементами, через которые я зацикливаюсь, см. Ниже:

def read_word_lists(path):
    import string
    with open(path, encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines[0].split(','):
            line = str(line)
            line = line.strip().lower()
            print(''.join(word.strip(string.punctuation) for word in line))
            print(line)
            print(''.join(word.strip(string.punctuation) for word in '"why, does this work?! and not above?"'))


read_word_lists('file.txt')

Результат такой:

trying to strip punctuation:  “you never”
originial:  “you never”
test:  why does this work and not above
trying to strip punctuation:  “you always
originial:  “you always"
test:  why does this work and not above
trying to strip punctuation:  ” “your problem is”
originial:  ” “your problem is”
test:  why does this work and not above
trying to strip punctuation:  “the trouble with you is”
originial:  “the trouble with you is”
test:  why does this work and not above

Есть какие-нибудь мысли, почему не работает вывод «попытка убрать пунктуацию»?

Редактировать

Исходный файл выглядит так, если это полезно:

"YOU NEVER”, “YOU ALWAYS", ” “YOUR PROBLEM IS”, “THE TROUBLE WITH YOU IS”

1 Ответ

2 голосов
/ 12 февраля 2020

Вы пытаетесь убрать пунктуацию Юникода, в то время как string.punctuation включает только пунктуацию ascii.

Вместо использования string.punctuation вы можете использовать приведенный ниже код для генерации строки, содержащей все символы пунктуации Юникода:

import unicodedata
import sys

punctuation = "".join((chr(i) for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith('P')))

Удачи!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...