2016-04-05 4 views
0

Итак, я пытался обработать целый абзац из случайной статьи. Детали утомительны, но одна вещь держит меня в замешательстве.Основная обработка строк на Python?

Вот мой код:

def prevword_ave_len(word):  
    count = 0 
    wordlength = 0 
    mystr = "Call me Ishmael. Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off - then, I account it high time to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship. There is nothing surprising in this. If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me." 
    l1 = mystr.split() 
    s1= list() 
    #print(l1) 

    if word in l1: 
     if l1.index(word) == 0: 
      return 0 
     else: 
      for element in l1:     
       s1.append(l1[l1.index(word) - 1]) #get that word to s1 list for future use 
       l1.pop(l1.index(word)) # delete the occurrence so that it will not mess up later on in this loop. 
       #print(s1) 
    else: 
     return False 

Моя цель состоит в том, чтобы определить, является ли слово существует в этом огромном списке слов. Однако, когда я пытался проверить это, кажется, что что-то не так, и я не могу понять это после двухчасового мучительного рассмотрения моего кода.

Моя ошибка, когда я пытаюсь это:

prevword_ave_len('the')  

Python возвращает False мне вместо истинного индекса 'the'. Как вы можете видеть, я пытаюсь получить этот индекс, а затем попытаюсь найти остальные индексы, чтобы я мог получить слово перед ними и сделать blablabla. Но это не главное, потому что я застрял прямо сейчас. Может кто-нибудь указать, что я делаю неправильно?

ОШИБКА

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "program.py", line 14, in prevword_ave_len 
    s1.append(l1[l1.index(word)]) 
    ValueError: 'the' is not in list 
+3

Можете ли вы исправить ваш отступы? – miradulo

+0

@DonkeyKong исправлено? –

+0

У вас есть два '' '' '' '' '' '' –

ответ

1

Youse если х в у:

paragraph = "Now is the time for all good men to come to the aid of their country" 

words = paragraph.split() 

if 'time' in words: 
    print "time is there" 
else: 
    print "not found" 

Вы можете захотеть сначала заменить некоторые символы (например, - -:;) с пространством

или вы можете использовать

i = paragraph.find(word) 

Это вернет 0 или индекс, в котором будет найдено слово.

+0

Вещь - я должен сохранить все это как это. Но что, если я использую цикл и напрямую сравниваю их по одному? Будет ли это работать? –

+0

Ваш абзац совсем не изменился. Я добавил второй метод - 1 строка –

0

Этот код возвращает 0, когда слово находится в первой позиции, False, если слово не найдено в абзаце, и ничего во всех остальных случаях. Не существует оператора возврата, который фактически возвращает индекс.

Попробуйте это:

def prevword_ave_len(word):  
    mystr = "Call me Ishmael. [...] ocean with me." 
    # Convert the string to an array of words 
    l1 = mystr.split() 

    # 'word' has been found in 'mystr' 
    if word in l1: 
    # return the index of 'word' in 'l1' 
    return l1.index(word) 
    else: 
    return False 

Кроме того, цикл по каждому элементу списка и удалить искомое слово из списка l1, чтобы поместить его в списке s1. В результате, когда ваша петля достигает следующего элемента, она пытается выполнить l1.index (word), но из предыдущего списка в списке был удален «word» (с list.pop()). Вот почему вы получаете ошибку, например «ValueError:« нет в списке ».

+0

Но, по крайней мере, машина не должна возвращать мне ничего, а не ошибку? –

+0

Какая ошибка возвращается? – Antwane

+0

Какая ошибка? вы не упомянули об ошибке ... – LexyStardust

0

Это кажется более простой способ делать вещи:

def prevword_ave_len(word):  
    mystr = "Call me Ishmael. Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off - then, I account it high time to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship. There is nothing surprising in this. If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me." 
    l1 = mystr.split() 
    s1 = list() 

    if not word in l1: 
     return False 

    while word in l1: 
     prevword = l1.pop(l1.index(word) - 1) 
     s1.append(prevword) #get that prevword to s1 list for future use 
     l1.pop(l1.index(word)) # remove that instance of word 

    return sum(len(w) for w in s1)/len(s1) # remember to use float(len(s1)) for Python 2.x 

print prevword_ave_len('the') 
Смежные вопросы