0

I have a txt file which contains a lot of information. In my script I open this file and remove unnecessary stuff by using in-built functions and regex, which is done in a for-loop.

Consider the txt file looking like this:

Monkey OFF OFF

Elephant ON ON

and so on...


My script:

x = 'XXX'
y = 'YYY'
value = ''
name = ''
func_file, functionality_file_context = open_func_file(args)
for fline in functionality_file_context:
    if fline.strip():  # ignore empty lines or lines with only whitespace
        commentregex = re.compile('^[^#]')  # ignore lines that start with comment (#)
        if (commentregex.match(fline)):
            # replace tabs with whitespace
            replacetab = re.compile(r'\s+')
            fline = replacetab.sub(' ', fline)

            function_line = fline.split(' ', 2)
            if len(function_line) != 3:
                exit("Something wrong with this line: " + fline.strip() + "\" in: " + func_file)

            name = x + function_line[0].strip() + y
            value = func_override_parameter_value(fline, func_file, function_line,value)
            print name + value


myDict = {
"Bike": 0,
"Car": 2,
name: value
}

another_function(args.path, myDict)

The func_override_parameter_value checks what value should be given if for example OFF OFF is matched etc. For example OFF OFF = 1, and ON ON = 2

By doing a print (the print name + value) I get all the names with the correct assigned value.

The open_func_file function:

def open_func_file(args):
    functionality_file_context = ''
    func_file = ''
    for func_file in args.functionality_file:
        functionality_file_context = open(func_file).readlines()
    return func_file, functionality_file_context

Now to the point:

I have a dict after this for-loop run which already contains some keys and values, for example:

myDict = {
"Bike": 0,
"Car": 2,
}

I want to add new keys and values from the file I just "parsed". I tried calling name and value inside the dict:

myDict = {
"Bike": 0,
"Car": 2,
name: value
}

The end result should be:

myDict = {
"Bike": 0,
"Car": 2,
"XXXMonkeyYYY": 1,
"XXXElephantYYY": 2
}

But this just gives me "Elephant": 2 and skips Monkey. Any idea how to solve this? The order does not matter.

Made an Edit

4
  • I'm confused... where is myDict in your code? Commented May 30, 2016 at 19:12
  • myDict is later called in another function which does some stuff. Commented May 30, 2016 at 19:15
  • how are we suppose to help you get the desired result for myDict if you don't even show the code that handles it? Commented May 30, 2016 at 19:17
  • Because that function has nothing to with the problem I am having. And plus I dont wanna post it here. But if u really want to know that function checks through files and tries to find names which are given in myDict and replace the current number with the number in myDict. Commented May 30, 2016 at 19:22

2 Answers 2

3

Put the code where you add to the dictionary inside the loop, next to the print. name and value can only hold one value at a time, they can't magically remember everything they've ever been and know the correct way to be inserted into your dict.

Sign up to request clarification or add additional context in comments.

Comments

1

In case the to the point guess and concise advice from @alex-hall is not explicit enough for the OP. Maybe something like this:

#! /usr/bin/env python
from __future__ import print_function
import re


def open_func_file(args):
    functionality_file_context = ''
    func_file = ''
    for func_file in args.functionality_file:
        functionality_file_context = open(func_file).readlines()
    return func_file, functionality_file_context


def func_override_parameter_value(
        fline, func_file, function_line, value):
    """Mocking the undefined function."""
    return 42

args = "some_file_name"
x = 'XXX'
y = 'YYY'
value = ''
name = ''
myDict = {
    "Bike": 0,
    "Car": 2,
}
commentregex = re.compile('^[^#]')  # ignore lines that start with comment (#)
func_file, functionality_file_context = open_func_file(args)
for fline in functionality_file_context:
    if fline.strip():  # ignore empty lines or lines with only whitespace
        if (commentregex.match(fline)):
            # replace tabs with whitespace
            replacetab = re.compile(r'\s+')
            fline = replacetab.sub(' ', fline)

            function_line = fline.split(' ', 2)
            if len(function_line) != 3:
                exit("Something wrong with this line: "
                     "" + fline.strip() + "\" in: " + func_file)

            name = x + function_line[0].strip() + y
            value = func_override_parameter_value(
                fline, func_file, function_line, value)
            print(name + str(value))
            myDict[name] = value

Hint: Scroll down to the last line of above code where it simply states:

myDict[name] = value

3 Comments

If this answer was built off of AlexHall's answer you at least owe him an upvote.
Hm we often help others in parallel, edit, submit and notice someone else also answered. That is normal, than we adapt, and vote, acknowledge. But "owing at least" sounds strange to me. I upvoted albeit I found the answer a bit terse and ironic for the obvious beginnerish coding style of the OP. Have a good day.
Of course, I have frequently ended up posting an answer that suggests the same thing as someone else, but the only time I have referenced another answer at the beginning of mine was when my answer was only an extension of theirs (there was no parallel) But I take it that was not the case so I apologize if I offended you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.