首页 > 解决方案 > 填充字典的输出与代码块中的打印语句不同

问题描述

这是我希望从中创建字典的文本文件的内容。我希望键是问题和问题选项列表作为关联值。

 1. Which of these best describes your physical frame?
 Small
 Medium
 Large
 
2. Which best describes your skin?
 Oily and soft with freckles or pimples
 Thick, oily, cool skin
 Dry
 
3. Which best describes your hair?
 Straight and fine
 Thick and lustrous
 Dry and curly
 
4. Which best describes your eyes?
 Large, pretty
 Small and dry
 Medium-sized; intense gaze
 
5. Which best describes how you talk?
 Fast and/or a lot!
 My words are sharp and concise.
 My speech is slow and calm.
 
6. What type of weather is your favorite?
 Warm
 Cool
 Cool and dry
 
7. How is your memory?
 I learn quickly, but I also forget quickly.
 I have a great memory!
 It takes me a while to commit something to memory, but once I do I don’t forget it.
 
8. Which best describes your personality?
 Responsible, nurturing, and sensitive
 Creative, joyful, and introspective
 Competitive, perceptive, and efficient
 
9. Which of these traits do you most identify with?
 I can be pretty stubborn.
 I get jealous easily.
 I’m often indecisive.
 
10. How about these traits? Which sounds the most like you?
 I’m very intuitive.
 I’m quite brave.
 I’m a loyal, faithful friend.
 
11. And these? Which sounds the most like you?
 I’m often restless.
 I can be irritable and impatient.
 I’m a loyal, faithful friend.
The following questions relate to how you act/feel when you’re under stress.
When you’re under stress do you tend to…

12. Experience insomnia?
 Yes
 No
 
13. Feel complacent?
 Yes
 No
 
14. Develop rashes or hives?
 Yes
 No
 
15. Lose weight?
 Yes
 No
 
16. Experience constipation or excess gas?
 Yes
 No
 
17. Overeat or lose your appetite?
 Yes
 No
 
18. Drink alcohol to excess?
 Yes
 No
 
19. Feel lazy or inert?
 Yes
 No
 
20. Easily lose your temper?
 Yes
 No
 
21. Retain water?
 Yes
 No
 
22. Seek change?
 Yes
 No
 
23. Sweat a lot or have excess body odor?
 Yes
 No
 
24. Feel anxious or fearful?
 Yes
 No
 
25. Eat hot, spicy foods?
 Yes
 No
 
26. Experience gastritis or ulcers?
 Yes
 No
 
27. Feel restless?
 Yes
 No
 
28. Sleep a lot?
 Yes
 No
 
29. Put on weight?
 Yes
 No

这是代码:

quiz = open("quiz.txt", "r")
quest_answer_dic = {}
answers = []
last_quest_lst =[] 
question = ""
for line in quiz:
    line = line.strip()

    if len(line.split()) > 0:

        if line[0].isdigit():

            if len(last_quest_lst)==0:
                question = line
                last_quest_lst.append(line)
            else:
                last_question = last_quest_lst.pop()
                print(last_question, end =" : ")
                print(answers)
                quest_answer_dic[last_question] = answers
                answers.clear()
                question = line
                last_quest_lst.append(question)

        else:
            answers.append(line)
            
print(quest_answer_dic)
quiz.close()

打印声明:

print(last_question, end =" : ")
print(answers)

给我我期望我的字典的输出:

1. Which of these best describes your physical frame? : ['Small', 'Medium', 'Large']
2. Which best describes your skin? : ['Oily and soft with freckles or pimples', 'Thick, oily, cool skin', 'Dry']
3. Which best describes your hair? : ['Straight and fine', 'Thick and lustrous', 'Dry and curly']
4. Which best describes your eyes? : ['Large, pretty', 'Small and dry', 'Medium-sized; intense gaze']
5. Which best describes how you talk? : ['Fast and/or a lot!', 'My words are sharp and concise.', 'My speech is slow and calm.']
6. What type of weather is your favorite? : ['Warm', 'Cool', 'Cool and dry']
7. How is your memory? : ['I learn quickly, but I also forget quickly.', 'I have a great memory!', 'It takes me a while to commit something to memory, but once I do I don’t forget it.']
8. Which best describes your personality? : ['Responsible, nurturing, and sensitive', 'Creative, joyful, and introspective', 'Competitive, perceptive, and efficient']
9. Which of these traits do you most identify with? : ['I can be pretty stubborn.', 'I get jealous easily.', 'I’m often indecisive.']
10. How about these traits? Which sounds the most like you? : ['I’m very intuitive.', 'I’m quite brave.', 'I’m a loyal, faithful friend.']
11. And these? Which sounds the most like you? : ['I’m often restless.', 'I can be irritable and impatient.', 'I’m a loyal, faithful friend.', 'The following questions relate to how you act/feel when you’re under stress.', 'When you’re under stress do you tend to…']
12. Experience insomnia? : ['Yes', 'No']
13. Feel complacent? : ['Yes', 'No']
14. Develop rashes or hives? : ['Yes', 'No']
15. Lose weight? : ['Yes', 'No']
16. Experience constipation or excess gas? : ['Yes', 'No']
17. Overeat or lose your appetite? : ['Yes', 'No']
18. Drink alcohol to excess? : ['Yes', 'No']
19. Feel lazy or inert? : ['Yes', 'No']
20. Easily lose your temper? : ['Yes', 'No']
21. Retain water? : ['Yes', 'No']
22. Seek change? : ['Yes', 'No']
23. Sweat a lot or have excess body odor? : ['Yes', 'No']
24. Feel anxious or fearful? : ['Yes', 'No']
25. Eat hot, spicy foods? : ['Yes', 'No']
26. Experience gastritis or ulcers? : ['Yes', 'No']
27. Feel restless? : ['Yes', 'No']
28. Sleep a lot? : ['Yes', 'No']

但是,当我打印我的 dic 的内容时,我得到:

'1. Which of these best describes your physical frame?': ['Yes', 'No'], '2. Which best describes your skin?': ['Yes', 'No'], '3. Which best describes your hair?': ['Yes', 'No'], '4. Which best describes your eyes?': ['Yes', 'No'], '5. Which best describes how you talk?': ['Yes', 'No'], '6. What type of weather is your favorite?': ['Yes', 'No'], '7. How is your memory?': ['Yes', 'No'], '8. Which best describes your personality?': ['Yes', 'No'], '9. Which of these traits do you most identify with?': ['Yes', 'No'], '10. How about these traits? Which sounds the most like you?': ['Yes', 'No'], '11. And these? Which sounds the most like you?': ['Yes', 'No'], '12. Experience insomnia?': ['Yes', 'No'], '13. Feel complacent?': ['Yes', 'No'], '14. Develop rashes or hives?': ['Yes', 'No'], '15. Lose weight?': ['Yes', 'No'], '16. Experience constipation or excess gas?': ['Yes', 'No'], '17. Overeat or lose your appetite?': ['Yes', 'No'], '18. Drink alcohol to excess?': ['Yes', 'No'], '19. Feel lazy or inert?': ['Yes', 'No'], '20. Easily lose your temper?': ['Yes', 'No'], '21. Retain water?': ['Yes', 'No'], '22. Seek change?': ['Yes', 'No'], '23. Sweat a lot or have excess body odor?': ['Yes', 'No'], '24. Feel anxious or fearful?': ['Yes', 'No'], '25. Eat hot, spicy foods?': ['Yes', 'No'], '26. Experience gastritis or ulcers?': ['Yes', 'No'], '27. Feel restless?': ['Yes', 'No'], '28. Sleep a lot?': ['Yes', 'No']}

标签: pythonfiledictionarytextprinting

解决方案


您可以使用defaultdict

根据我收集到的信息,您可以查看句子中的第一个字符。如果字符是数字,则行是键,否则为值。

对于每个值行,您需要附加到字典中。

from collections import defaultdict

with open('text.txt') as f:
    lns = f.readlines()

dct = defaultdict(list)
key = ""

for ln in lns:
    ln = ln.strip("\n")
    if ln:
        if ln[0].isdigit():
            key = ln
        else:
            dct[key].append(ln)

for val in dct.items():
    print(val)

结果:

('1. Which of these best describes your physical frame?', ['Small', 'Medium', 'Large'])
('2. Which best describes your skin?', ['Oily and soft with freckles or pimples', 'Thick, oily, cool skin', 'Dry'])
('3. Which best describes your hair?', ['Straight and fine', 'Thick and lustrous', 'Dry and curly'])
('4. Which best describes your eyes?', ['Large, pretty', 'Small and dry', 'Medium-sized; intense gaze'])
('5. Which best describes how you talk?', ['Fast and/or a lot!', 'My words are sharp and concise.', 'My speech is slow and calm.'])
('6. What type of weather is your favorite?', ['Warm', 'Cool', 'Cool and dry'])
('7. How is your memory?', ['I learn quickly, but I also forget quickly.', 'I have a great memory!', 'It takes me a while to commit something to memory, but once I do I don’t forget it.'])
('8. Which best describes your personality?', ['Responsible, nurturing, and sensitive', 'Creative, joyful, and introspective', 'Competitive, perceptive, and efficient'])
('9. Which of these traits do you most identify with?', ['I can be pretty stubborn.', 'I get jealous easily.', 'I’m often indecisive.'])
('10. How about these traits? Which sounds the most like you?', ['I’m very intuitive.', 'I’m quite brave.', 'I’m a loyal, faithful friend.'])
('11. And these? Which sounds the most like you?', ['I’m often restless.', 'I can be irritable and impatient.', 'I’m a loyal, faithful friend.', 'The following questions relate to how you act/feel when you’re under stress.', 'When you’re under stress do you tend to…'])
('12. Experience insomnia?', ['Yes', 'No'])
('13. Feel complacent?', ['Yes', 'No'])
('14. Develop rashes or hives?', ['Yes', 'No'])
('15. Lose weight?', ['Yes', 'No'])
('16. Experience constipation or excess gas?', ['Yes', 'No'])
('17. Overeat or lose your appetite?', ['Yes', 'No'])
('18. Drink alcohol to excess?', ['Yes', 'No'])
('19. Feel lazy or inert?', ['Yes', 'No'])
('20. Easily lose your temper?', ['Yes', 'No'])
('21. Retain water?', ['Yes', 'No'])
('22. Seek change?', ['Yes', 'No'])
('23. Sweat a lot or have excess body odor?', ['Yes', 'No'])
('24. Feel anxious or fearful?', ['Yes', 'No'])
('25. Eat hot, spicy foods?', ['Yes', 'No'])
('26. Experience gastritis or ulcers?', ['Yes', 'No'])
('27. Feel restless?', ['Yes', 'No'])
('28. Sleep a lot?', ['Yes', 'No'])
('29. Put on weight?', ['Yes', 'No'])

推荐阅读