user4659009
user4659009

Reputation: 685

Python: How to pass in only one variable into a lambda function?

My code is reading in a text file line by line. Each line is then trimmed of all whitespace to one space character and based on whether it matches the pattern it is then written to either the matched_data_file or the unmatched_data_file. I have to make use of lambda in this particular example. I think the error lies with the following line but I'm not 100% sure:

success(line=row) if pattern.match(line) else failure(line=row)

Any help is greatly appreciated, thanks in advance!

I get the following error message:

Traceback (most recent call last): File "model_dev_txt_to_csv.py", line 26, in process(source_filename) File "model_dev_txt_to_csv.py", line 23, in process process_line(line, lambda: write_csv(m, line), lambda: write_csv(u, line)) File "model_dev_txt_to_csv.py", line 12, in process_line return success(line=row) if pattern.match(line) else failure(line=row) TypeError: () got an unexpected keyword argument 'line'

The following is my current code:

import re
import csv

pattern = re.compile("([0-9]+) +([0-9\.-]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+)")
source_filename = "track_param_hist.txt"
matched_data_file = "good_hist_csv.csv"
unmatched_data_file = "bad_hist_csv.csv"

def process_line(line, success, failure):
    # Make sure all whitespace is reduced to one space character
    row = (' '.join(line.split())).split(' ')
    success(line=row) if pattern.match(line) else failure(line=row)

def write_csv(file, line):
    csv.writer(file).writerow(line)

def process(source):
    print("Script for splitting text file into two separate csvs...")
    with open(matched_data_file, 'w') as m:
        with open(unmatched_data_file, 'w') as u:
            with open(source) as f:
                for line in f:
                    process_line(line, lambda: write_csv(m, line), lambda: write_csv(u, line))

if __name__ == "__main__":
    process(source_filename)

Upvotes: 0

Views: 352

Answers (1)

Mariusz Jamro
Mariusz Jamro

Reputation: 31643

Lambda expression's syntax in Python is:

lambda [list of arguments]: <expression>

In your code you do not have any arguments defined for your lambdas. You need to add an argument named line before the : character to make your code work:

lambda line: write_csv(m, line), lambda line: write_csv(u, line)

Upvotes: 2

Related Questions