【问题标题】:Edit lines in txt file of varying length编辑不同长度的txt文件中的行
【发布时间】:2012-12-07 16:41:06
【问题描述】:

所以我有多个格式如下的 txt 文档:

james  
M  
18  
72   
170  
teresa  
F  
19  
63  
115  

有些只有两个名称,有些只有 50 个。基本上,我要做的是格式化信息,以便将其重写为具有以下格式的新文本文件:

Name: james  
Gender: M  
Age: 18  
Height: 72  
Weight: 170  
Name: teresa  
Gender: F  
Age: 19  
Height: 63  
Weight: 115  

到目前为止,我有:

def tagInfo(fileName):
    with open(fileName) as infile, open("altered.txt","w") as outfile:
        for i,line in enumerate(infile):
            if i == 0:
                outfile.write("Name: "+line.strip()+"\n")
            if i == 1:
                outfile.write("Gender: "+line.strip()+"\n")
            if i == 2:
                outfile.write("Age: "+line.strip()+"\n")
            if i == 3:
                outfile.write("Height: "+line.strip()+"\n")
            if i == 4:
                outfile.write("Weight: "+line.strip()+"\n")
    outfile.close()

这个程序所做的只是编辑前 5 行。我正在努力做到这一点,所以如果我给它一个 50 人要更改的列表,它会更改所有 50 人的信息,而不仅仅是前五行。使用我目前的解决方案,这是不可能的。我不知道从哪里开始,我觉得最好放弃一切并采取不同的方法。

你们有什么解决办法吗?

【问题讨论】:

  • 与您的问题并不真正相关,但我很惊讶没有人指出outfile.close() 是多余的。使用 with 语句的全部意义在于文件上下文管理器将在退出 with 语句块时关闭文件。

标签: python io python-3.x


【解决方案1】:

如果您的文件有固定的字段列表,则将字段定义为列表,并使用带模数的行号作为索引来获取字段名称:

fields = ('Name', 'Gender', 'Age', 'Height', 'Weight')

def tagInfo(fileName):
    with open(fileName) as infile, open("altered.txt","w") as outfile:
        for i, line in enumerate(infile):
            field = fields[i % len(fields)]
            outfile.write('{0}: {1}\n'.format(field, line))

如果字段超过5个,您可以根据需要添加。

【讨论】:

  • +1。但如果文件不是由机器生成的,我至少会添加一些基本的、非常简单的检查,例如:字母字符串、F/M、1 到 150 的整数等。
【解决方案2】:

将您的检查更改为i % 5 == 0 等。这样检查将在每五行返回一次。

if i % 5 == 0:
    outfile.write("Name: "+line.strip()+"\n")
elif i % 5 == 1:
    outfile.write("Gender: "+line.strip()+"\n")
elif i % 5 == 2:
    outfile.write("Age: "+line.strip()+"\n")
elif i % 5 == 3:
    outfile.write("Height: "+line.strip()+"\n")
elif i % 5 == 4:
    outfile.write("Weight: "+line.strip()+"\n")

【讨论】:

    【解决方案3】:

    解决方案

    修改方案

    只需使用mod,简短而简单:

    def tagInfo(fileName):
        with open(fileName) as infile, open("altered.txt","w") as outfile:
            for i,line in enumerate(infile):
                if i % 5 == 0:
                    outfile.write("Name: "+line.strip()+"\n")
                elif i % 5 == 1:
                    outfile.write("Gender: "+line.strip()+"\n")
                elif i % 5 == 2:
                    outfile.write("Age: "+line.strip()+"\n")
                elif i % 5 == 3:
                    outfile.write("Height: "+line.strip()+"\n")
                elif i % 5 == 4:
                    outfile.write("Weight: "+line.strip()+"\n")
        outfile.close()
    


    重写解决方案

    这个解决方案会好得多,因为它可以消除代码中的很多欺骗,更不用说让它更干净了:

    fields = ("Name", "Gender", "Age", "Height", "Weight") # can be edited as per req.s
    l = len(fields)
    
    def tagInfo(fileName):
        with open(fileName) as infile, open("altered.txt","w") as outfile:
            for (index, s) in enumerate(infile):
                 field = fields[index % l]
                 outfile.write("{}: {}\n".format(field, s.strip())
        outfile.close()
    


    模组功能

    来自docs:

    %(模)运算符从第一个参数除以第二个参数产生余数。数字参数首先转换为通用类型。零右参数引发 ZeroDivisionError 异常。参数可以是浮点数,例如,3.14%0.7 等于 0.34(因为 3.14 等于 4*0.7 + 0.34。)模运算符总是产生与第二个操作数(或零)具有相同符号的结果;结果的绝对值严格小于第二个操作数的绝对值。


    TL;DR:

    modulo function(也称为 mod 函数)基本上只是给出除第一个数字的余数。到第二个。所以a % b = cmp(b, 0) * abs(a - (a // b))(我想)。

    【讨论】:

    • 这是最简单的解决方案,沿用原始代码。 (另一种方法:编写一个函数,从一个已经打开的文件中读取五行,然后一遍又一遍地调用它,直到文件末尾。这对于更复杂的情况会更好。)
    • @alexis 第二个解决方案是什么?我认为更好,因为它需要最少的修改来添加字段或任何东西。它遵循 KISS 和 DRY。
    • 我将其添加为新答案。
    • field = fields[index] + ": " - 如果您不想出现 IndexError,您可能想在此处使用 fields[index % 5]。
    • @poke 糟糕,错字。真的应该是... % len(fields)
    【解决方案4】:

    解决问题的另一种方法

    fields = ('Name', 'Gender', 'Age', 'Height', 'Weight')
    with open("infile.txt") as fin, open("altered.txt","w") as fout:
        while True:
            data =  ''.join(map(':'.join,zip(fields,fin)))
            if data:
                fout.write(data)
            else:
                break
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多