Python:填写文本文件中的行

时间:2017-11-16 01:52:07

标签: python-2.7

我有一个文本文件,设置如下:

#include <stdio.h>
#include <string.h>
#include <postgres.h>
#include <port.h>
#include <fmgr.h>
#include <stdlib.h>
#include <builtins.h>

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

extern PGDLLEXPORT Datum CLEANSING_STRING(PG_FUNCTION_ARGS);

PG_FUNCTION_INFO_V1(CLEANSING_STRING);
Datum CLEANSING_STRING(PG_FUNCTION_ARGS)
{

    // Get Arg
    text *arg1 = (text *)PG_GETARG_TEXT_P(0);

    // Text to Char[]
    char *arg;
    arg = text_to_cstring(arg1);

    // UTF8 to Sjis
    //Char *sjisChar[] = foo(arg);  // something like that..

    // Copied from other system.(Assumes that the character code is sjis.)
    cleansingString(sjisChar);
    replaceStrimg(sjisChar);

    // Sjis to UTF8
    //arg = bar(sjisChar);  // something like that..

    //Char[] to Text and Return
    PG_RETURN_TEXT_P(cstring_to_text(arg));
}

使用以下代码。我可以读取所有行并删除在我的密钥文件中具有条件的特定行。

Category One
      1234X DD/MM/YYYY $1,234.56
      5678X DD/MM/YYYY $7,890.12
      9012X DD/MM/YYYY $3,456.78
Category One Total     $12,581.46
Category Two
      1234X DD/MM/YYYY $1,234.56
      5678X DD/MM/YYYY $7,890.12
      9012X DD/MM/YYYY $3,456.78
Category Two Total     $12,581.46

但是,我想在每一行添加特定的“类别”,以便它如下所示。

keyfile = "keys.txt"
#this is the list of variables to pull from the test file
testfile = "test.txt"
#this is my original file obtained. The one that needs to be read and lines extracted from
testoutput = open('output.txt', 'w')
keys = [key for key in (line.strip() for line in open(keyfile)) if key]

with open(testfile) as f:
for line in f:
for key in keys:
    if key in line:
       testoutput.write(line)

非常感谢任何帮助。

0 个答案:

没有答案