как убрать пунктуацию из списка - PullRequest
0 голосов
/ 29 декабря 2018

Могу ли я помочь кому-нибудь с этим кодом, теперь я получаю 'test2' так же, как и 'test', если я проверяю строку, она работает хорошо, но как список она не работает должным образом

 punc = set(string.punctuation)
 test=[" course content good though textbook badly written.not got energy 
 though seems good union.it distance course i'm sure facilities.n/an/ain 
last year offer poor terms academic personal. seems un become overwhelmed trying become run"]

test2 = ''.join(w for w in test if w not in punc)
 print(test2)

Iхочу убрать все знаки препинания

Ответы [ 3 ]

0 голосов
/ 29 декабря 2018
import string
test=[" course content good though textbook badly written.not got energy though seems good union.it distance course i'm sure facilities.n/an/ain last year offer poor terms academic personal. seems un become overwhelmed trying become run"]
test2 = ''.join(w for w in test[0] if w not in string.punctuation )
print(test2)

Если в списке несколько строк

import string
test=["Hi There!"," course content good though textbook badly written.not got energy though seems good union.it distance course i'm sure facilities.n/an/ain last year offer poor terms academic personal. seems un become overwhelmed trying become run"]
#if there are multiple string in the list
for x in test:
    print(''.join(w for w in x if w not in string.punctuation ))
# If there are multiple strings in the list and you want to join all of them togather
print(''.join(w for w in [x for x in test] if w not in string.punctuation )) 

Если вам нужно добавить его в переменную списка

import string
test2=[]
test=["Hi There!"," course content good though textbook badly written.not got energy though seems good union.it distance course i'm sure facilities.n/an/ain last year offer poor terms academic personal. seems un become overwhelmed trying become run"]
#if there are multiple string in the list
for x in test:
    test2.append(''.join(w for w in x if w not in string.punctuation ))
print(test2)
0 голосов
/ 29 декабря 2018

Самый быстрый (и, возможно, самый питонский способ сделать это) использует перевод.

import string
test=["Hi There!"," course content good though textbook badly written.not got energy though seems good union.it distance course i'm sure facilities.n/an/ain last year offer poor terms academic personal. seems un become overwhelmed trying become run"]

# Create a translate table that translates all punctuation to nothing
transtable = {ord(a):None for a in string.punctuation}

# Apply the translation to all strings in the list
[s.translate(transtable) for s in test]
0 голосов
/ 29 декабря 2018

Поскольку test - это список, «for w in test» вернет первый элемент списка, являющийся полной строкой.Таким образом, вам необходимо получить доступ ко всем элементам 'w', чтобы фактически проверить все отдельные символы строки.

...