将字符串拆分为三个分隔符,并将它们添加到不同的列表中

时间:2015-03-13 20:24:45

标签: python regex string

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

Poles|Magnet|?|Battery

游戏的作用是由用户猜测填充“?”的内容一部分。

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

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

我不知道如何让程序执行此操作:

  1. 将前四个分成一个列表。
  2. 我做到了这一点:

    # 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。然后可以针对该用户的输入进行测试。

    3. 到目前为止,这是完整的事情:

      # 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,以便在显示时不会显示! {{1}} 1}}表示答案?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以使用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

答案 2 :(得分:0)

根据我的观点,如果我们可以添加一个分隔符,一切都将如此易于使用:D 注意:您可能有超过4个选项

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

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

在这种情况下,我们不认为如果您像这样实施游戏,则需要对此问题提供更多帮助。它现在很简单 -

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

此外,请添加评论,如果您仍想要解决上一个问题,我也可以尝试。

答案 3 :(得分:0)

我可能会对接受的答案采取类似的方法,但我会稍微区别对待它。你必须在这里意识到的是,你拥有的是一个以逗号分隔的值文件。 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