Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 需要进行文件解析_Python_Csv_Parsing_Quote - Fatal编程技术网

Python 需要进行文件解析

Python 需要进行文件解析,python,csv,parsing,quote,Python,Csv,Parsing,Quote,我需要处理这样的文件 keyword,synonym,bidirectional 5487500j,54875,false 76x76,76 x 76,true feuille,"papier,ramette",false 7843000j,78430,false 我需要把它转换成一个dict: {'5487500j':'54875', '76x76':'76 x 76','feuille':['papier','ramette'], '7843000j':'78430'}

我需要处理这样的文件

keyword,synonym,bidirectional
5487500j,54875,false
76x76,76 x 76,true
feuille,"papier,ramette",false
7843000j,78430,false
我需要把它转换成一个dict:

{'5487500j':'54875', '76x76':'76 x 76','feuille':['papier','ramette'], '7843000j':'78430'}

我无法以任何快速而优雅的方式成功处理

这是一个非常简单的解析练习,你真的应该自己尝试解决它

下面是我的解决方案,使用
find()
rfind()
查找第一个和最后一个逗号的索引,将行拆分为块。第一个块和中间块将用作dict中的键:值对。中间块可能需要一些额外的解析和调整,请参阅下面的代码

def parse(line):
    first = line[:line.find(',')]
    last = line[line.rfind(','):]
    mid = line.replace(first, '').replace(last, '').strip(',')
    #print(first, mid)
    if ',' in mid:
        mid = mid.strip('"')
        mid = mid.split(',')
    return {first: mid}


txt = \
'''
keyword,synonym,bidirectional
5487500j,54875,false
76x76,76 x 76,true
feuille,"papier,ramette",false
7843000j,78430,false
'''

r = {}
for line in txt.split('\n'):
    if line:
        if line.startswith('keyword'):
            continue
        r.update(parse(line))
        
print(r)

{'5487500j': '54875', '76x76': '76 x 76', 'feuille': ['papier', 'ramette'], '7843000j': '78430'}

首先让我具体说明我从你的要求中了解到了什么

  • 您输入的是一个csv文件,带有可选的带引号的字段:ok csv模块可以解析它
  • 每个记录的第一个字段将用作字典中的键
  • 第三个字段被忽略
  • 第二个字段将是字典中的值。如果它不包含逗号,将按原样使用,否则该值将是一个拆分列表
在尝试编写任何代码之前,您应该始终用简单的英语(或您的母语是什么)写下您想要做的详细说明。因为编码部分应该是规范的翻译

这里的Python代码(对于我的规范…)可以是:

with open(inputfile) as fd:
    rd = csv.reader(fd)  # you files uses the default for quoting and delimiter
    _ = next(rd)         # skip header line
    result = {}
    for row in rd:
        result[row[0]] = row[1].split(',') if ',' in row[1] else row[1]
事实上,理解比循环更像蟒蛇:

    result = {row[0]: row[1].split(',') if ',' in row[1] else row[1]
              for row in rd}

请包括到目前为止您已经尝试过的代码。以及对底层逻辑的一些解释-例如,为什么
“papier,ramette”
被拆分为列表,第三列是否影响解析,等等。请阅读Python文档中的
string.find()
string.rfind()