0

プログラムでテキスト ファイルから 5 単語ごとに取得し、それを 1 つの文字列に配置しようとしています。たとえば、「パイはおいしくて、ブルーベリー ストロベリーやライムなど、さまざまな種類があるので、誰もがパイを食べるのが好きです」と入力した場合、プログラムは「Everyone because plus types and.」と出力するはずです。最初の単語から始めて、5 番目の単語ごとに取得する必要があります。これを行う方法について混乱しています。以下は私のコードです。最後の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これらの条件が両方とも当てはまるわけではないため、背後にあるアイデアが何であったかはわかりません。5 番目の単語ごとに選択する場合は、次のようにします。

if i % 5 == 0:

で割った余りが であるかどうかをチェックi5ます0

ただし、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']
>>>

したがって、5 番目の単語ごとに取得するには、次のようにします。

>>> 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 に答える