1

質問と 2 つの回答の 3 つの部分で構成される一連の短い文字列を解析する必要があります。文字列は一貫した形式に従います。

これは、「answer_option_1 は引用符で囲まれています」「answer_option_2 は引用符で囲まれています」という質問です。

質問の部分と、一重引用符または二重引用符で囲まれた 2 つの回答の選択肢を特定する必要があります。

例:今日の空は何色ですか。「青」か「灰色」
か 「ミシガン州」「オハイオ州」の試合に勝つのはどちらか

Pythonでこれを行うにはどうすればよいですか?

4

4 に答える 4

1
>>> import re
>>> s = "Who will win the game 'Michigan' 'Ohio State'"
>>> re.match(r'(.+)\s+([\'"])(.+?)\2\s+([\'"])(.+?)\4', s).groups()
('Who will win the game', "'", 'Michigan', "'", 'Ohio State')
于 2010-11-11T16:23:01.293 に答える
1

あなたが言うようにフォーマットが単純である場合(つまり、例のようではない場合)、正規表現は必要ありません。ちょうどsplit行:

>>> line = 'What color is the sky today? "blue" "grey"'.strip('"')
>>> questions, answers = line.split('"', 1)
>>> answer1, answer2 = answers.split('" "')
>>> questions
'What color is the sky today? '
>>> answer1
'blue'
>>> answer2
'grey'
于 2010-11-11T16:34:15.027 に答える
0

1 つの可能性は、正規表現を使用できることです。

import re
robj = re.compile(r'^(.*) [\"\'](.*)[\"\'].*[\"\'](.*)[\"\']')
str1 = "Who will win the game 'Michigan' 'Ohio State'"
r1 = robj.match(str1)
print r1.groups()
str2 = 'What color is the sky today? "blue" or "grey"'
r2 = robj.match(str2)
r2.groups()

出力:

('Who will win the game', 'Michigan', 'Ohio State')
('What color is the sky today?', 'blue', 'grey')
于 2010-11-11T16:18:52.283 に答える
0

Pyparsing は、入力テキストの可変性に適応するソリューションを提供します。

questions = """\
What color is the sky today? "blue" or "grey"
Who will win the game 'Michigan' 'Ohio State'""".splitlines()

from pyparsing import *

quotedString.setParseAction(removeQuotes)
q_and_a = SkipTo(quotedString)("Q") + delimitedList(quotedString, Optional("or"))("A")

for qn in questions:
    print qn
    qa = q_and_a.parseString(qn)
    print "qa.Q", qa.Q
    print "qa.A", qa.A
    print

印刷します:

What color is the sky today? "blue" or "grey"
qa.Q What color is the sky today? 
qa.A ['blue', 'grey']

Who will win the game 'Michigan' 'Ohio State'
qa.Q Who will win the game 
qa.A ['Michigan', 'Ohio State']
于 2010-12-20T22:53:04.120 に答える