user2581724
user2581724

Reputation: 245

Python 3.3: How to grab every 5th word in a text file?

I'm trying to have my program grab every fifth word from a text file and place it in a single string. For instance, if I typed "Everyone likes to eat pie because it tastes so good plus it comes in many varieties such as blueberry strawberry and lime" then the program should print out "Everyone because plus varieties and." I must start with the very first word and grab every fifth word after. I'm confused on how to do this. Below is my code, everything runs fine except the last 5 lines.

#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)

Upvotes: 0

Views: 4609

Answers (5)

martineau
martineau

Reputation: 123463

Using your method of defining words withstr.split(), either of the following will do what you want:

textInput = """\
I'm trying to have my program grab every fifth word from a text file and
place it in a single string. For instance, if I typed "Everyone likes to
eat pie because it tastes so good plus it comes in many varieties such
as blueberry strawberry and lime" then the program should print out
"Everyone because plus varieties and." I must start with the very first
word and grab every fifth word after. I'm confused on how to do this.
Below is my code, everything runs fine except the last 5 lines."""

everyfive = ' '.join(word for i,word in enumerate(textInput.split()) if not i%5)

# or more succinctly
everyfive = ' '.join(textInput.split()[::5])

print(repr(everyfive))

Either way, the output will be:

"I'm program from place string. typed pie good many strawberry program because 
 must first fifth on Below runs 5"

The shorter and (consequently much faster and simpler) version using the[::5]notation is based on something called "slicing", which all sequences support in Python. The general concept is described in the documentation near the beginning of the Sequences section.

Upvotes: 2

Simon
Simon

Reputation: 10841

The output from split() is a list of words in the string. e.g.:

>>> "The quick brown fox jumped over the lazy dog and then back again".split()
['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog', 'and',
'then', 'back', 'again']
>>>

Thus, to get every fifth word:

>>> for i,s in enumerate("The quick brown fox jumped over the lazy dog and then
back again".split()):
...     if i%5 == 0: print (s)
...
jumped
and
>>>>

Upvotes: 0

Michael Swartz
Michael Swartz

Reputation: 858

Here's my basic solution. I'm sure some will say it's not 'pythonic' but it gets the job done.

someString = "Everyone likes to eat pie because it tastes so good plus it comes in many varieties such as blueberry strawberry and lime"
someList = someString.split()
loadString = ''
i = 0
for s in range(len(someList)):
    if i < len(someList) - 1:
        loadString += someList[i] + ' '
        i += 5
print loadString.rstrip(' ')

Upvotes: 0

user2357112
user2357112

Reputation: 280500

for i in textInput.split() loops over the words in textInput, not the indices. If you want both indices and words, you want

for i, word in enumerate(textInput.split()):

I don't know what the idea was behind i <= 4 and i >= 6, since those conditions can't both be true. If you want to pick every fifth word, you want

if i % 5 == 0:

which checks if the remainder upon dividing i by 5 is 0.

However, you don't need the if statement at all. You can just slice the list given by split to get every 5th element:

# Iterate over every 5th word in textInput.
for word in textInput.split()[::5]:
    print(word)

Upvotes: 2

ranendra
ranendra

Reputation: 2512

You can split the sentences with the spaces and then increment the array's index by 5 to get the desired outcome.

textInput = "Everyone likes to eat pie because it tastes so good plus it comes in many varieties such as blueberry strawberry and lime"
steps = 5
words = textInput.split()
for x in xrange(1, len(words), steps):
    print words[x]

#OUTOUT
Everyone
because
plus
varieties
and

Upvotes: 0

Related Questions