Как использовать Python для чтения текстового файла и передачи в словарь? - PullRequest
0 голосов
/ 19 декабря 2018
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

Я пытаюсь прочитать текстовый файл, который выглядит как выше, и я хочу перенести его в словарь.Вопросы в виде ключей и четыре отзыва в качестве значений.

{"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 голосов
/ 19 декабря 2018

В зависимости от ваших критериев для вопроса .Здесь я предполагаю, что вопрос заканчивается на ?

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)
0 голосов
/ 19 декабря 2018

Не очень элегантно, но этот код работает:

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
0 голосов
/ 19 декабря 2018
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)
...