如何使用Python读取文本文件并转入字典?

How to use Python read a text file and transfer to dictionary?

1. How do you like this product?
As someone who wears glasses for distance, but not contacts I have struggled with vision on the slopes
At this price, I'm very happy with the B1. They were very comfortable
I wore these all winter for 10 weeks of skiing!
These are cheap in price yes but they do what they're supposed to
2. Do you have any recommendations?
The product is a defect, and the quality was bad
Yes, I like this product and it didn't fog up when I was skiing
I won't refer my friend to buy this product.
So far so good

我正在尝试读取一个如上所示的 txt 文件,我想将其传输到字典中。 以问题为键,然后是四个评论作为值。

{"1. How do you like this product?":["As someone who wears glasses for distance, but not contacts I have struggled with vision on the slopes","At this price, I'm very happy with the B1. They were very comfortable","I wore these all winter for 10 weeks of skiing!","These are cheap in price yes but they do what they're supposed to","As someone who wears glasses for distance, but not contacts I have struggled with vision on the slopes"],"2. Do you have any recommendations?":["The product is a defect, and the quality was bad","Yes, I like this product and it didn't fog up when I was skiing","I won't refer my friend to buy this product.","So far so good"]

感谢您的帮助

d = {}
with open('file') as file:
    lines = file.readlines()
    key = None
    for line in lines:
        if line[0].isdigit():
            key = line
            d[line] = []
        else:
            d[key].append(line)

取决于您问题的标准。这里我假设一个问题以 ?

结尾
with open('input_file.txt') as f:
  out_dict = {}
  for line in f.readlines():
    # strip out blank characters at the beginning and the end
    line = line.strip()

    # a question ends with ?
    if line[:-1] == '?':
       current_key=line
       out_dict[current_key] = []
    else:
       out_dict[current_key].append(line)

不是很优雅,但这段代码有效:

outputDict = {}
with open('sampleText', 'r') as f:
    tempKey = None
    templist = []
    for line in f.readlines():
        if line[0].isdigit() and line[1] == '.':
            if tempKey != None:
                outputDict[tempKey] = templist
                templist = []
                tempKey = line.rstrip('\n')
                print('found a key that is not the first')
                print(line)
                print(tempKey)
            else:
                tempKey = line.rstrip('\n')
                print('found first key')
                print(line)
                print(tempKey)
        else:
            templist.append(line.rstrip('\n'))
            print('found val')
            print(line)
    outputDict[tempKey] = templist