Как обрабатывать пустую строку, ненужную строку и \ n при преобразовании входного файла в CSV-файл - PullRequest
0 голосов
/ 08 ноября 2019

Ниже приведен пример данных во входном файле. Мне нужно обработать этот файл и превратить его в CSV-файл. С некоторой помощью я смог преобразовать его в CSV-файл. Однако не полностью преобразован в CSV, так как я не могу обработать \ n, пустую строку (2-я строка) и пустую строку (4-я строка). Кроме того, мне нужна помощь, чтобы отфильтровать тип транзакции, т. Е. Избежать «переписать» тип транзакции

{"transaction_type": "new", "policynum": 4994949}  
44uu094u4  
{"transaction_type": "renewal", "policynum": 3848848,"reason": "Impressed with \n the Service"}  

{"transaction_type": "cancel", "policynum": 49494949, "cancel_table":[{"cancel_cd": "AU"}, {"cancel_cd": "AA"}]}
{"transaction_type": "rewrite", "policynum": 5634549}

Ниже приведен код

import ast
import csv

with open('test_policy', 'r') as in_f, open('test_policy.csv', 'w') as out_f:
    data = in_f.readlines()
    writer = csv.DictWriter(
        out_f,
        fieldnames=[
            'transaction_type', 'policynum', 'cancel_cd','reason'],lineterminator='\n',
        extrasaction='ignore')
    writer.writeheader()

    for row in data:
        dict_row = ast.literal_eval(row)
        if 'cancel_table' in dict_row:
            cancel_table = dict_row['cancel_table']
            cancel_cd= []
            for cancel_row in cancel_table:
                cancel_cd.append(cancel_row['cancel_cd'])            
            dict_row['cancel_cd'] = ','.join(cancel_cd)

        writer.writerow(dict_row)

Ниже приведен мой вывод, не учитывающий пустую строку, пустую строку итип транзакции "перезаписать".

тип транзакции, policynum, cancel_cd, причина
new, 4994949 ,,
продление, 3848848 ,, "Впечатлено
Услуга"
отмена, 49494949, "AU, AA",

Ожидаемый результат

тип_такции транзакции, policynum, cancel_cd, причина
новый, 4994949 ,,
обновление, 3848848 ,, "Впечатлен сервисом"
отмена, 49494949, "AU, AA",

1 Ответ

0 голосов
/ 09 ноября 2019

Хм, я пытаюсь их исправить, но я не знаю, как работает файл CSV, но мой маленький возраст, когда мне будет предложено запустить этот код, прежде чем конвертировать файл.

txt = {"transaction_type": "renewal",
       "policynum": 3848848,
       "reason": "Impressed with \n the Service"}
newTxt = {}

for i,j in txt.items():
    # local var (temporar)
    lastX = ""
    correctJ = ""

    # check if in J is ascii white space "\n" and get it out
    if "\n" in f"b'{j}'":
        j = j.replace("\n", "")

    # for grammar purpose check if
    # J have at least one space
    if " " in str(j):
        # if yes check it closer (one by one)
        for x in ([j[y:y+1] for y in range(0, len(j), 1)]):
            # if 2 spaces are consecutive pass the last one
            if x == " " and lastX == " ":
                pass
            # if not update correctJ with new values
            else:
                correctJ += x
            # remember what was the last value checked
            lastX = x

        # at the end make J to be the correctJ (just in case J has not grammar errors)
        j = correctJ

    # add the corrections to a new dictionary
    newTxt[i]=j

# show the resoult
print(f"txt = {txt}\nnewTxt = {newTxt}")

Терминал:

txt = {'transaction_type': 'renewal', 'policynum': 3848848, 'reason': 'Impressed with \n the Service'}
newTxt = {'transaction_type': 'renewal', 'policynum': 3848848, 'reason': 'Impressed with the Service'}

Process finished with exit code 0
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...