0

我试图让我的程序从一个文本文件中抓取每五个单词并将其放在一个字符串中。例如,如果我输入“每个人都喜欢吃馅饼,因为它味道很好,而且它有很多品种,例如蓝莓草莓和酸橙”,那么程序应该打印出“每个人都因为加上品种和”。我必须从第一个单词开始,然后每五个单词抓一次。我对如何做到这一点感到困惑。下面是我的代码,除了最后 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)
4

5 回答 5

2

使用用 定义单词的方法,str.split()以下任一方法都可以满足您的要求:

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

无论哪种方式,输出将是:

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

使用该符号的更短且(因此更快更简单)的版本[::5]基于称为“切片”的东西,Python 中的所有序列都支持这种东西。一般概念在序列部分开头附近的文档中进行了描述。

于 2013-07-15T01:07:09.927 回答
2

for i in textInput.split()循环遍历 中的单词textInput,而不是索引。如果你想要索引和单词,你想要

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

我不知道背后的想法是什么i <= 4 and i >= 6,因为这些条件不可能都成立。如果你想选择每五个单词,你想要

if i % 5 == 0:

它检查除以时的余数i是否50.

但是,您根本不需要 if 语句。您可以对 split 给出的列表进行切片以获取每 5 个元素:

# Iterate over every 5th word in textInput.
for word in textInput.split()[::5]:
    print(word)
于 2013-07-15T01:47:31.583 回答
0

的输出split()是字符串中的单词列表。例如:

>>> "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']
>>>

因此,要获得每五个单词:

>>> 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
>>>>
于 2013-07-15T01:08:34.807 回答
0

您可以用空格分割句子,然后将数组的索引增加 5 以获得所需的结果。

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
于 2013-07-15T01:11:52.340 回答
0

这是我的基本解决方案。我敢肯定,有些人会说这不是“pythonic”,但它可以完成工作。

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(' ')
于 2013-07-15T12:06:26.403 回答