Итак, я пытался обработать целый абзац из случайной статьи. Детали утомительны, но одна вещь держит меня в замешательстве.Основная обработка строк на 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
Можете ли вы исправить ваш отступы? – miradulo
@DonkeyKong исправлено? –
У вас есть два '' '' '' '' '' '' –