我試圖讓我的程序從文本文件中抓取每第五個單詞並將其放在單個字符串中。例如,如果我輸入「每個人都喜歡吃餡餅,因爲它的味道非常好,並且它有許多品種,比如藍莓草莓和酸橙」,那麼該程序應該打印出「所有人,因爲加上品種和。」。我必須從第一個單詞開始,然後每隔五分鐘抓一個單詞。我很困惑如何做到這一點。下面是我的代碼,除了最後5行外,一切都運行正常。Python 3.3:如何抓取文本文件中的每個第5個單詞?
#Prompt the user to enter a block of text.
done = False
textInput = ""
while(done == False):
nextInput= input()
if nextInput== "EOF":
break
else:
textInput += nextInput
#Prompt the user to select an option from the Text Analyzer Menu.
print("Welcome to the Text Analyzer Menu! Select an option by typing a number"
"\n1. shortest word"
"\n2. longest word"
"\n3. most common word"
"\n4. left-column secret message!"
"\n5. fifth-words secret message!"
"\n6. word count"
"\n7. quit")
#Set option to 0.
option = 0
#Use the 'while' to keep looping until the user types in Option 7.
while option !=7:
option = int(input())
#I'm confused here. This is where I'm stuck. Is the 'for' loop correct for this `#situation?`
#If the user selects Option 5,
elif option == 5:
for i in textInput.split():
if i <= 4 and i >= 6:
print(textInput)
忽略其他問題,我很好奇你什麼時候''i'既是'<= 4' *也是*'> = 6'。 – user2357112