【问题标题】:Reading a line from a text file using commas as delimiter使用逗号作为分隔符从文本文件中读取一行
【发布时间】:2016-01-11 16:54:49
【问题描述】:

我正在尝试从文本文件中读取不同的行。

目前我有一个程序可以从文本文件中读取以下类型的行,如果它遵循这种格式:

6361550850261,SHOWALL
APN="3"
IGF=15
VOW=117
VWD=12
[+][+]52

使用此代码:

def make_dict(data):
    return dict((line.split(None, 1)[0], line)for line in data)

def process(infile, outfile, keywords):
    keys = [[k[0], k[1], 0] for k in keywords]
    endk = None
    with open(infile, 'rb') as fdin:
        with open(outfile, 'ab') as fdout:
            fdout.write("|<" + words + ">|" + "\r\n")
            for line in fdin:
                if endk is not None:
                    fdout.write(line)
                    if line.find(endk) >= 0:
                        fdout.write("\r\n")
                        endk = None
                else:
                    for k in keys:
                        index = line.find(k[0])
                        if index >= 0:
                            fdout.write(line[index + len(k[0]):].lstrip())
                            endk = k[1]
                            k[2] += 1
    if endk is not None:
        print 'Serial Number not Found'
        raise Exception(endk + "Not found before end of file")
    return keys

infile 是我从中读取的文件,outfile 是输出文本文件,keywords 是我在文本文件中查找的序列号。

这适用于这种类型的格式化文本。 但是,如果我有以下文本:

*GS,6361550850261,211635181215,,APN;"3",IGF:A;15;VOW:117,VWD;12,ADC:12.40;[+][+]52

请注意,我使用逗号作为分隔符来分隔数据,而不是空格。

我怎样才能使用与顶部文本文件相同的想法。

所以总的来说,我只是想读取使用这种格式而不是其他格式的行。

编辑:

作为输出示例: 如果我有这条线: *GS,6361550850261,211635181215,,APN;"3",IGF:A;15;VOW:117,VWD;12,ADC:12.40;[+][+]52

进入这个: *GS 6361550850261 211635181215 APN:"3" IGF:A;15 VOW:117 VWD:12 ADC:12.40

【问题讨论】:

  • 你试过line.split(',')吗?
  • csv 模块有什么问题?
  • 我没有尝试过 CSV 模块,因为我一直试图改变我当前的 process 定义以适应它。我会考虑使用csv
  • 您能展示一下您的预期输出吗?该脚本是否需要与您的两个示例输入一起使用?
  • @MartinEvans 我添加了一个输出示例

标签: python text file-io delimiter


【解决方案1】:

用逗号分割字符串:

>>> s = '*GS,6361550850261,211635181215,,APN;"3",IGF:A;15;VOW:117,VWD;12,ADC:12.40;[+][+]52'
>>> lines = [line for line in s.split(',') if line]
>>> lines
['*GS', '6361550850261', '211635181215', 'APN;"3"', 'IGF:A;15;VOW:117', 'VWD;12', 'ADC:12.40;[+][+]52']

现在您可以遍历这些行以按您认为合适的方式处理它们。

请注意,此代码原样可能无法解决您的问题,因为您的示例语法存在差异。请注意并重新调整我的答案以满足您的需求。

【讨论】:

    【解决方案2】:

    对于您给定的输入示例,以下函数应为您提供所需的结果:

    import csv
    
    def process(infile, outfile):
        with open(infile, 'rb') as f_input, open(outfile, 'w') as f_output:
            for cols in csv.reader(f_input):
                output = cols[0:3]                          # *GS + 2 numbers
                output.append(cols[4].replace(';', ':'))    # APN
                output.extend(cols[5].rsplit(';', 1))       # IGF and VOW
                output.append(cols[6].replace(';', ':'))    # VWD
                output.append(cols[7].rsplit(';', 1)[0])    # ADC
                f_output.write('\n'.join(output))
                f_output.write('\n')
    

    这将生成一个包含以下内容的输出文件:

    *GS
    6361550850261
    211635181215
    APN:"3"
    IGF:A;15
    VOW:117
    VWD:12
    ADC:12.40
    

    Python csv 模块会自动将文件的每一行拆分为条目列表。默认情况下,这适用于逗号。

    您可能需要提供更多示例行,因为这完全取决于现有行的格式。

    使用 Python 2.7.9 测试

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      • 1970-01-01
      相关资源
      最近更新 更多