如何使用Python读取文本文件并传输到字典?

时间:2018-12-19 19:58:20

标签: python dictionary text file-read

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"]

感谢您的帮助

3 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:0)

根据您的问题标准。在这里,我假设一个问题以?

结尾
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)

答案 2 :(得分:0)

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

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