2015-02-12 2 views
0

Напишите функцию list_of_words, которая берет список строк, как указано выше, и возвращает список отдельных слов со всеми пробелами и пунктуацией (кроме апострофов/одинарных кавычек).using strip() в python

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

def list_of_words(list_str): 
    m = [] 
    for i in list_str: 
     i.strip('.') 
     i.strip(',') 
     i.strip('!') 
     m = m+i.split() 
    return m 

print(list_of_words(["Four score and seven years ago, our fathers brought forth on", 
    "this continent a new nation, conceived in liberty and dedicated", 
    "to the proposition that all men are created equal. Now we are", 
    " engaged in a great  civil war, testing whether that nation, or any", 
    "nation so conceived and so dedicated, can long endure!"]) 
+0

Мне нужно использовать метод strip() или split(), а не метод replace. –

+0

Краткая версия: 'return [word.strip ('.,!') Для части в list_str для слова в part.split()]' – Matthias

ответ

2

Один из самых простых способов, чтобы очистить некоторые знаки препинания и несколько пробелов будут использовать re.sub функции.

import re 

sentence_list = ["Four score and seven years ago, our fathers brought forth on", 
       "this continent a new nation, conceived in liberty and dedicated", 
       "to the proposition that all men are created equal. Now we are", 
       " engaged in a great  civil war, testing whether that nation, or any", 
       "nation so conceived and so dedicated, can long endure!"] 

sentences = [re.sub('([,.!]){1,}', '', sentence).strip() for sentence in sentence_list] 
words = ' '.join([re.sub('([" "]){2,}', ' ', sentence).strip() for sentence in sentences]) 

print words 
"Four score and seven years ago our fathers brought forth on this continent a new nation conceived in liberty and dedicated to the proposition that all men are created equal Now we are engaged in a great civil war testing whether that nation or any nation so conceived and so dedicated can long endure" 
1

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

for i in list_str: 
    i = i.strip('.') 
    i = i.strip(',') 
    i = i.strip('!') 
    .... 

на второй ноте strip удаляет указанные символы только на начало и конец строки. Если вы хотите удалить символы между строкой, вы должны рассмотреть replace

0

Как было предложено ранее, вам необходимо назначить i.strip() на номер i. И, как упоминалось ранее, метод замены лучше. Вот пример, использующий метод замены:

def list_of_words(list_str:list)->list: 
    m=[] 
    for i in list_str: 
     i = i.replace('.','') 
     i = i.replace(',','') 
     i = i.replace('!','') 
     m.extend(i.split()) 
    return m 

print(list_of_words([ "Four score and seven years ago, our fathers brought forth on", 
    "this continent a new nation, conceived in liberty and dedicated", 
    "to the proposition that all men are created equal. Now we are", 
    " engaged in a great  civil war, testing whether that nation, or any", 
    "nation so conceived and so dedicated, can long endure! ]) 

Как вы можете заметить, я также заменил m=m+i.split() с m.append(i.split()), чтобы сделать его более удобным для чтения.

1

Вы можете использовать регулярные выражения, как описано в this question. По существу,

import re 

i = re.sub('[.,!]', '', i) 
0

Было бы лучше не полагаться на свой собственный список знаков препинания, но и использовать питона один, и как другие имеют указатель, использование регулярных выражений, чтобы удалить символы:

punctuations = re.sub("[`']", "", string.punctuation) 
i = re.sub("[" + punctuations + "]", "", i) 

Там также string.whitespace, хотя раскол позаботится о них для вас.