Hello! Please tell me what the error is:

punctum='!?.' for a in range(len(words)): #этот цикл должен брать слово а в массиве words, проверять, #есть ли в слове перед ним (b) на конце точка,вопр.или # воскл. знак, и, если он там есть, удалить слово а b=words[a+1] if words[a][-1] in punctum: del words[b] 

it is necessary that in the array ['words', 'words.', 'words', 'words'] the words are deleted: (

  • 2
    Darkness. словоА словоБ. словоВ словоГ словоА словоБ. словоВ словоГ - you need to delete WordV and WordG (because after deleting, WordV will have WordB before wordB. (with a dot.) So? (Ie, do all words after a word with ?!.
  • 2
    Did you even run this code? You have b - is first a word, and then the index in the list of words; besides, in the line b = words [a + 1] you have a way out of the list. Well, the most important thing is that after deleting several words, the original range remains the same, which means the last indices in it will be invalid. - gkuznets

3 answers 3

It is better to create a new array list and copy the elements there, than to change the old one. In general, there are many ways to filter arrays. Example: select all the lines immediately following the line ending in! or ?

 #!/usr/bin/python test = ".!?" before = ["1.","2","3!","4","5?","6","7"] after = [] for a, b in zip(before, before[1:]): if a[-1] in test: after.append(b) print after 

Check

['2', '4', '6']

  • The idea is correct, but in my opinion the original problem is solved like this: after.append (before [0]) for a, b in zip (before, before [1:]): if a [-1] not in test: after.append (b) - gkuznets

I would do something like this:

 class PunctuationFilter: def __init__(self, chars): self.skip = False self.chars = chars def __call__(self, x): if self.skip: self.skip = False return False if x[-1] in self.chars: self.skip = True return True filtred = filter(PunctuationFilter('.?!'), ['словоа', 'словоб.', 'словов', 'словог']) 

    I would do something like this:

     >>> punctuation_marks = ('!', '?', '.') >>> words = ['one', 'two!', 'three?', 'four.'] >>> words = [word for word in words if not word.endswith(punctuation_marks)] >>> words ... ['one'] 

    Documentation