regex python中的字符串排序

w8f9ii69  于 2023-02-10  发布在  Python
关注(0)|答案(1)|浏览(113)

初学者在这里。我正在创建测验项目,我有字符串:

s = "1. You are _____ me.
A) older B) oldest C) older than D) older then
2. New York is _____ Paris.
A) dirty B) dirtier than C) the dirtiest D) dirtier
3. Prague is one of the _____ cities in Europe,
A) most beautiful B) more beautiful
C) beautiful D) the most beautiful
4. How many children _____ they _____?
A) have / got B) have / get
C) does / got D) has / got"

我需要切片它测试编号。结果必须看起来像这样:

result = {
    "test_number": test number,
    "question": question text,
    "options": [test options],
}
wj8zmpe1

wj8zmpe11#

你可以从字符串s中提取信息,方法是将它拆分成单独的行,然后解析每一行以提取相关信息。

s = "1. You are _____ me.\nA) older B) oldest C) older than D) older then\n2. New York is _____ Paris.\nA) dirty B) dirtier than C) the dirtiest D) dirtier\n3. Prague is one of the _____ cities in Europe,\nA) most beautiful B) more beautiful\nC) beautiful D) the most beautiful\n4. How many children _____ they _____?\nA) have / got B) have / get\nC) does / got D) has / got"

lines = s.split("\n")
tests = []
current_test = {}
for line in lines:
    if line.startswith("\n"):
        tests.append(current_test)
        current_test = {}
    elif line.startswith("\n"):
        current_test["test_number"] = int(line.split(".")[0])
        current_test["question"] = line.split(".")[1].strip()
    elif line.startswith("A"):
        current_test["options"] = line.split(" ")[1:]
tests.append(current_test)

print(tests)

这段代码将创建一个字典列表,其中每个字典代表一个测试,并包含测试编号、问题文本和选项列表。

相关问题