【问题标题】:Split a string by three delimiters, and adding them to different lists通过三个分隔符拆分字符串,并将它们添加到不同的列表中
【发布时间】:2015-03-13 20:24:45
【问题描述】:

我正在用 Python 制作一个问答游戏。到目前为止,程序读入了一个文件。文件中是这样的:

Poles|Magnet|?|Battery

游戏通过用户猜测“?”中的内容来进行。部分。

我已经可以通过在 | 字符处拆分将字符串拆分为 4 个单独的部分,但现在我想将其添加到末尾:

Poles|Magnet|?|Battery/!Charge/Ends/Magic/Metal

我不知道如何让程序这样做:

  1. 将前四个拆分为一个列表。

我已经完成了这一点:

# Read questions in from a file.
with open("questions.txt", "r") as questions:
    data = questions.read().split("|")
    for x in range(0,4):
        print(data[x])
  1. 将后四个拆分为另一个列表。

  2. 然后查看哪个开头有!(表示它是正确答案)并将其放入字符串中,例如answer。然后可以针对此测试用户的输入。

这是目前为止的全部内容:

# Quick Thinker!

import os

def buildQuestions():
# Read questions in from a file.
with open("questions.txt", "r") as questions:
    data = questions.read().split("|")
    for x in range(0,4):
        print(data[x])


def intro():
print("        ____        _      _      _______ _     _       _             _ ")
print("       / __ \      (_)    | |    |__   __| |   (_)     | |           | |")
print("      | |  | |_   _ _  ___| | __    | |  | |__  _ _ __ | | _____ _ __| |")
print("      | |  | | | | | |/ __| |/ /    | |  | '_ \| | '_ \| |/ / _ \ '__| |")
print("      | |__| | |_| | | (__|   <     | |  | | | | | | | |   <  __/ |  |_|")
print("        \___\_\\__,_|_|\___|_|\_\    |_|  |_| |_|_|_| |_|_|\_\___|_|  (_)")
print("                                                                  ")
input("")
os.system("cls")
print("Welcome to the game!")
print("In QUICKTHINKER, you must select the correct missing entry from a sequence.")
print("")
print("For Example: ")
print("")
print("PEACE | CHAOS | CREATION | ?")
print("")
print("A: MANUFACTURE")
print("B: BUILD")
print("C: DESTRUCTION")
print("")
print("The correct answer for this would be DESTRUCTION.")
print("")
print("There will be, more or less, no pattern between questions.")
print("Each have their own logic.")
input("")
os.system("cls")

intro()
buildQuestions()
input("")

任何帮助表示赞赏。 谢谢

编辑

不知道是否将其变成另一个问题,但是我将如何从answers 列表中删除!,以便在显示时没有任何! 可以表示答案?

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    这应该可行。首先它被| 分割。最后一个元素包含你的答案。然后我们从键中删除答案。现在我们将答案分成它们的部分。最后我们通过搜索!得到正确答案并将其保存在字符串answer中。

    with open("questions.txt", "r") as questions:
        keys = questions.read().split('|')
        answers = keys[3]
        keys[3] = keys[3].split('/', 1)[0]
    
        answers = answers.split('/')[1:]
    
        answer = [x for x in answers if '!' in x][0].strip('!')
    
        answers = [x.strip('!') for x in answers]
    
        print(keys)
        print(answers)
        print(answer)
    

    输出

    ['Poles', 'Magnet', '?', 'Battery']
    ['Charge', 'Ends', 'Magic', 'Metal']
    Charge
    

    【讨论】:

    • 完美运行。谢谢!
    • 不知道是否将其变成另一个问题,但是我将如何从answers 列表中删除!,以便在显示时没有任何@ 987654328@那里表示答案?
    • 我更新了我的答案。要从答案中删除 !,您可以对列表的每个元素使用 strip 函数。
    【解决方案2】:

    你可以使用re.split:

    s = "Poles|Magnet|?|Battery/!Charge/Ends/Magic/Metal"
    
    spl = re.split("[|/]",s)
    a,b = spl[:4],spl[4:]
    print(a,b)
    (['Poles', 'Magnet', '?', 'Battery'], ['!Charge', 'Ends', 'Magic', 'Metal'])
    

    如果您只想要具有! 的字符串:

    answer = next(x for x in spl if x.startswith("!"))
    print(answer)
    !Charge
    

    如果您需要知道它在哪个列表中:

    answer_a,answer_b = next((x for x in a if x.startswith("!")),""), next((x for x in b if x.startswith("!")),"")
    print("The answer {} was in list1".format(answer_a) if answer_a else "The answer {} was in list2".format(answer_b))
    
    The answer !Charge was in list2
    

    【讨论】:

      【解决方案3】:

      根据我的观点,如果我们可以再添加一个分隔符,一切都会变得如此简单:D 注意:有时您可能有超过 4 个选项

      Poles|Magnet|?|Battery-!Charge/Ends/Magic/Metal 
      

      Poles|Magnet|?|Battery-Ends/!Charge/Magic/Metal
      

      在这种情况下,我们不t need so complicated answers ;) I dont 认为如果你这样实现你的游戏,你需要更多的帮助来解决这个问题。现在就这么简单-

      首先,用 "-" 分开,你会得到 2 个列表。然后,用“|”拆分list1和 list2 与“/”。 :D

      另外,请添加评论,如果您仍然想要解决以前的问题,我也可以尝试。

      【讨论】:

        【解决方案4】:

        我可能会对接受的答案采取类似的方法,但我会以不同的方式处理它。您必须在这里意识到的是,您拥有的是一个逗号分隔值文件。 Suuuure,你没有使用逗号,但这仍然是一个csv 文件。既然你有一个csv 文件,那就用csv 模块来处理吧!

        import csv
        
        questions = []
        # we'll build dicts with questions of the format:
        # {'prompts': ['Poles', 'Magnet', 'Battery'],
        #  'answers: ['Ends','Charge','Magic','Metal'],
        #  'correct: 'Charge'}
        
        with open("path/to/file.txt") as infile:
            reader = csv.reader(infile, delimiter="|")
            for row in reader:
                d = {}
                prompts = row[:-1] # everything but the last entry is a prompt
                answers = []
                for ans in row[-1].split("/"):
                    if ans.startswith("!")
                        correct = ans.strip("!")
                    answers.append(ans.strip("!"))
                d['prompts'] = prompts
                d['answers'] = answers
                d['correct'] = correct
                questions.append(d)
        

        这一切都完成后,您将得到如下列表:

        questions = [ {'prompts': ['Poles', 'Magnet', 'Battery'],
                       'answers: ['Ends','Charge','Magic','Metal'],
                       'correct: 'Charge'},
                      {'prompts': ['Peace','Chaos','Creation'],
                       'answers: ['Manufacture','Build','Destruction'],
                       'correct: 'Destruction'}, ... ]
        

        这很有用,因为你的整个测验是:

        for question in questions:
            print(" | ".join(question['prompts']) + " | ?")
            print()
            mapping = dict(zip(question['answers'], "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
            # this will make sure we can test the answer afterwards
            for answer in question['answers']:
                print(mapping[answer] + ". " + answer)
            response = input(">> ")
            correct_response = mapping[question['correct']]
            if response == correct_response:
                # handle correct answers here. Maybe score += 1?
            else:
                # handle incorrect answers here
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-07-15
          • 2021-10-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多