如何在字符串Python中获取符号之间的文本

2024-06-16 05:54:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个程序,自动回答网站上的问题,我将答案存储在一个文件中,但我不知道如何读取文件中的符号。我需要得到的问题和答案都是粗体的

这是文件中每个问题的外观。最后的逗号是第一个问题和第二个问题之间的分界

{“填写以下语句:将状态从---(1)---更改为气体称为---(2)---”:{“['1:液体;2:蒸发”,“1:液体;2:熔化”,“1:固体;2:蒸发”,“1:固体;2:熔化]”: “1:液体;2:蒸发”,“['1:液体;2:沉积','1:液体;2:升华','1:固体;2:沉积','1:固体;2:升华']:“1:固体;2:升华”


Tags: 文件答案程序网站状态符号语句外观
2条回答

假设您有文本格式的数据(即扩展名为.txt的文本文件)

# To read text from .txt file

with open("temp.txt", "r") as f:
    content = f.read()

arr = content.split("},") 
# Above line will return an array but "}," will be removed from the string. We don't want "," but we need "}"
# For that below code will help.

i = 0
while i < len(arr)-1:  # "-1" because, "}" will not be removed from the last, so we need to keep the last element as it is
    arr[i] += "}"
    i += 1

# Now we have a list of strings, which can be converted into dicts
# For that...
from ast import literal_eval

i = 0
while i<len(arr):
    arr[i] = literal_eval(arr[i])
    i += 1


# Now you have your data in the form of array of dicts
# Sample code to get questions, options and answers

questions, options, answers = [], [], []

for dicts in arr:
    i = 0
    for key, val in dicts.items():
        if i == 0:
            questions.append(key)

        temp = val
        for key, val in temp.items():
            options.append(key)
            answers.append(val)

# Now you have arrays of questions, options and answers.
# 0 indexed question related to 0 indexed options and 0 indexed answer, similarly for 1, 2, 3 and so on.

# EXAMPLE
print("que1 = ", questions[0])
print("options = ", options[0])
print("ans = ", answers[0])

您可以尝试将字符串转换为dict,然后使用dict.items()

相关问题 更多 >