Python comparing two same string returns with false [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'll put some of my code bellow to explain the issue, but basically what I'm trying to do it to compare within a function - a string & a line that will include only that string.
I have the list as follows:
org_tasks = ['general_static ', 'host_general_static ',etc....]
which I'm passing to function with a filename (python file)
my_dict = createDictFromTaskList(ref_ver, org_tasks)
def createDictFromTaskList(prm_fl,tasks_list):
final_dict = {}
for task in tasks_list:
print getTransformedDic(prm_fl, str('CurrentTaskParams.' + task))
return final_dict
which calls:
def getTransformedDic(prm_fl,dic_name): # transforms string to dictionary
"turns dictionary values from type variable into a string"
newDic = ""
dicToChange = getOldDicAsString(prm_fl,dic_name)
if dicToChange is None: return None
dicToChange = dicToChange[len(dic_name) + 3:] #here i get none for some reason
dicToChange = dicToChange.replace('"', "'")
for line in dicToChange.splitlines():
transformedLine = ''.join(line.split())
transformedLine = transformedLine.strip()
if transformedLine.startswith('#'): continue
IsLineBelongsToDic = transformedLine.split(':')
if len(IsLineBelongsToDic) > 1:
if transformedLine[-1:] == ",":
valueAsString = '"%s",' % transformedLine[len(IsLineBelongsToDic[0]) + 1:-1]
else:
valueAsString = '"%s",' % transformedLine[len(IsLineBelongsToDic[0]) + 1:]
line = ' ' + IsLineBelongsToDic[0] + ' : ' + valueAsString
newDic += '%s' % line + '\n'
try:
value = ast.literal_eval(newDic[:-1])
except SyntaxError:
return None
else:
return value
def getOldDicAsString(prm_fl, dic_name):
"return a string that contains dictionary"
with open(prm_fl) as f:
file_data = f.read()
recordLines = False
dictionary = ""
for line in file_data.splitlines():
transformedLine = ''.join(line.split())
transformedLine = transformedLine.strip()
taskName = transformedLine.split('=')[0]
print taskName ,dic_name # here i can see they are the same
if taskName == dic_name or recordLines:
recordLines = True
dictionary += line + '\n'
if transformedLine == "}":
return dictionary
the file i work with looks as follows (according to list I've mentioned before):
...
CurrentTaskParams.general_static = {
'is_enable' : 'true'
}
CurrentTaskParams.host_general_static = {
'is_enable' : 'true'
}
...
after adding few prints I've seen that when for example I compare
CurrentTaskParams.general_static
--> which was passed as parameter
to the line containing this string (after striping in from spaces & '{' & '=' )
I dont append the dictionary string (meaning my 'if' returns false)
any help would be great,
thanks!

The following minimal example replicates your source data and your code block:
file_data = """
CurrentTaskParams.general_static = {
'is_enable' : 'true'
}
CurrentTaskParams.host_general_static = {
'is_enable' : 'true'
}
"""
dic_name = 'CurrentTaskParams.general_static'
for line in file_data.splitlines():
transformedLine = ''.join(line.split())
transformedLine = transformedLine.strip()
taskName = transformedLine.split('=')[0]
print("'%s'" % taskName, "'%s'" % dic_name, taskName == dic_name)
Running this it correctly picks up the line in question:
'' 'CurrentTaskParams.general_static' False
'CurrentTaskParams.general_static' 'CurrentTaskParams.general_static' True
''is_enable':'true'' 'CurrentTaskParams.general_static' False
'}' 'CurrentTaskParams.general_static' False
'CurrentTaskParams.host_general_static' 'CurrentTaskParams.general_static' False
''is_enable':'true'' 'CurrentTaskParams.general_static' False
'}' 'CurrentTaskParams.general_static' False
With a working example it is difficult to debug the problem(!) but I suspect this means the problem is somewhere else.
In your example code you list the org tasks with the trailing space still in place, is this intentional?
org_tasks = ['general_static ', 'host_general_static ',etc....]
I would suggest you try printing the data you believe to be matching but wrapped in quotes (see above) as this will help better highlight any leading/trailing spaces in your strings.

Related

How would I format python code using python?

Let's say I've got this code in python:
total=0for i in range(100):print(i)if i > 50:total=total+i
How would I make an algorithm in python to format this python code into the code below:
total=0
for i in range(100):
print(i)
if i > 50:
total=total+i
Assume that everything is nested under each other, such that another statement would be assumed to be inside the if block.
This was quite a fun exercise! I'm running out of juice so just posting this as is. It works on your example but probably not much for anything more complex.
code_block = "total=0for i in range(100):print(i)if i > 50:total=total+iprint('finished')"
code_block_b = "def okay() {print('ff')while True:print('blbl')break}"
line_break_before = ['for', 'while', 'if', 'print', 'break', '}']
line_break_after = [':', '{']
indent_chars = [':', '{']
unindent_chars = ['}']
# Add line breaks before keywords
for kw in line_break_before:
kw_indexes = [idx for idx in range(len(code_block)) if code_block[idx:idx + len(kw)] == kw]
for kw_idx in kw_indexes[::-1]:
code_block = code_block[:kw_idx] + '\n' + code_block[kw_idx:]
# Add line breaks after other keywords if not present already
for kw in line_break_after:
kw_indexes = [idx for idx in range(len(code_block)) if code_block[idx:idx + len(kw)] == kw]
for kw_idx in kw_indexes[::-1]:
if code_block[kw_idx + 1: kw_idx + 2] != '\n':
code_block = code_block[:kw_idx + 1] + '\n' + code_block[kw_idx + 1:]
# Add indentation
indent = 0
formatted_code_lines = []
for line in code_block.split('\n'):
if line[-1] in unindent_chars:
indent = 0
formatted_code_lines.append(' ' * indent)
if line[-1] in indent_chars:
indent += 4
formatted_code_lines.append(line + '\n')
code_block = ''.join(formatted_code_lines)
print(code_block)
The basic premise for formatting is based around keywords. There are keys that require a line break before, and keys that require a line break after them. After that, the indentation was counted +4 spaces for every line after each : symbol. I tested some formatting with braces too in code_block_b.
Output a
total=0
for i in range(100):
print(i)
if i > 50:
total=total+i
Output b
def okay() {
print('ff')
while True:
print('blbl')
break
}

How to write an INI file with ConfigParser with duplicate options

I want to write an INI file with duplicate options,ie:
[test]
foo = value1
foo = value2
xxx = yyy
With ConfigParser.set only the last value is writed.
config = ConfigParser.ConfigParser()
config.read('example.cfg')
config.add_section('test')
config.set('test', service['foo'], service['value1'])
config.set('test', service['foo'], service['value2'])
config.set('test', service['xxx'], service['yyy'])
The result is:
[test]
foo = value2
xxx = yyy
Is there any way?
It looks like it isn't possible in a simple way. The default way ConfigParser stores is with dict's, i.e. one value per unique key.
In a similar question Python's ConfigParser unique keys per section the suggestions are to go with:
CongfigObj
Patched version of epydoc
i have a simple custom .ini parser in python (built for another project), which uses a list to store values but only if they are not in key=value format. if key=value then last key will be held since these are stored in a dictionary
The parser can also parse nested sections like:
[SECTION1][SECTION2]
key1=value1
; etc..
The code is below, it is easy to modify to store key/value in list instead of dictionary or even detect multiple key and rename to avoid collisions (e.g key, key$1 second key with same key value key and so on). use/modify as needed
##
#
# Simple .ini Parser for Python 2.x, 3.x
#
##
import re
class Ini_Parser():
"""Simple .ini parser for Python"""
NL = None
ACTUAL = {
'\\n' : "\n",
'\\t' : "\t",
'\\v' : "\v",
'\\f' : "\f"
}
def parseStr(s, q):
_self = Ini_Parser
endq = s.find(q, 1)
quoted = s[1:endq]
rem = s[endq+1:].strip()
for c,actual in _self.ACTUAL.items():
quoted = ( actual ).join( quoted.split( c ) )
quoted = ( '\\' ).join( quoted.split( '\\\\' ) )
return quoted, rem
def fromString(s, keysList=True, rootSection='_'):
_self = Ini_Parser
comments = [';', '#']
if rootSection: rootSection = str(rootSection)
else: rootSection = '_'
if not _self.NL:
_self.NL = re.compile(r'\n\r|\r\n|\r|\n')
sections = {}
currentSection = str(rootSection)
if keysList:
sections[currentSection] = { '__list__' : [] }
else:
sections[currentSection] = { }
currentRoot = sections
# parse the lines
lines = re.split(_self.NL, str(s))
# parse it line-by-line
for line in lines:
# strip the line of extra spaces
line = line.strip()
lenline = len(line)
# comment or empty line, skip it
if not lenline or (line[0] in comments): continue
linestartswith = line[0]
# section line
if '['==linestartswith:
SECTION = True
# parse any sub-sections
while '['==linestartswith:
if SECTION:
currentRoot = sections
else:
currentRoot = currentRoot[currentSection]
SECTION = False
endsection = line.find(']', 1)
currentSection = line[1:endsection]
if currentSection not in currentRoot:
if keysList:
currentRoot[currentSection] = { '__list__' : [] }
else:
currentRoot[currentSection] = { }
# has sub-section ??
line = line[endsection+1:].strip()
if not len(line): break
linestartswith = line[0]
# key-value pairs
else:
# quoted string
if '"'==linestartswith or "'"==linestartswith:
key, line = _self.parseStr(line, linestartswith)
# key-value pair
if line.find('=', 0)>-1:
line = line.split('=')
line.pop(0)
value = "=".join(line).strip()
valuestartswith = value[0]
# quoted value
if '"'==valuestartswith or "'"==valuestartswith:
value, rem = _self.parseStr(value, valuestartswith)
currentRoot[currentSection][key] = value
# single value
else:
if keysList:
currentRoot[currentSection]['__list__'].append(key)
else:
currentRoot[currentSection][key] = True
# un-quoted string
else:
line = line.split('=')
key = line.pop(0).strip()
# single value
if 1>len(line):
if keysList:
currentRoot[currentSection]['__list__'].append(key)
else:
currentRoot[currentSection][key] = True
# key-value pair
else:
value = "=".join(line).strip()
valuestartswith = value[0]
# quoted value
if '"'==valuestartswith or "'"==valuestartswith:
value, rem = _self.parseStr(value, valuestartswith)
currentRoot[currentSection][key] = value
return sections
def fromFile(filename, keysList=True, rootSection='_'):
s = ''
with open(filename, 'r') as f: s = f.read()
return Ini_Parser.fromString(s, keysList, rootSection)
def walk(o, key=None, top='', q='', EOL="\n"):
s = ''
if len(o):
o = dict(o)
if key: keys = [key]
else: keys = o.keys()
for section in keys:
keyvals = o[section]
if not len(keyvals): continue
s += str(top) + "[" + str(section) + "]" + EOL
if ('__list__' in keyvals) and len(keyvals['__list__']):
# only values as a list
s += q + (q+EOL+q).join(keyvals['__list__']) + q + EOL
del keyvals['__list__']
if len(keyvals):
for k,v in keyvals.items():
if not len(v): continue
if isinstance(v, dict) or isinstance(v, list):
# sub-section
s += Ini_Parser.walk(keyvals, k, top + "[" + str(section) + "]", q, EOL)
else:
# key-value pair
s += q+k+q+ '=' +q+v+q + EOL
s += EOL
return s
def toString(o, rootSection='_', quote=False, EOL="\n"):
s = ''
if rootSection: root = str(rootSection)
else: root = '_'
if quote: q = '"'
else: q = ''
# dump the root section first, if exists
if root in o:
section = dict(o[root])
llist = None
if '__list__' in section:
llist = section['__list__']
if llist and isinstance(llist, list) and len(llist):
s += q + (q+EOL+q).join(llist) + q + EOL
del section['__list__']
for k,v in section.items():
if not len(v): continue
s += q+k+q+ '=' +q+v+q + EOL
s += EOL
del o[root]
# walk the sections and sub-sections, if any
s += Ini_Parser.walk(o, None, '', q, EOL)
return s
def toFile(filename, o, rootSection='_', quote=False, EOL="\n"):
with open(filename, 'w') as f:
f.write( Ini_Parser.toString(o, rootSection, quote, EOL) )
# for use with 'import *'
__all__ = [ 'Ini_Parser' ]

Python - searching if string is in file

I want to search for string in file and if there is string make action and if there isn´t string make other action, but from this code:
itcontains = self.textCtrl2.GetValue()
self.textCtrl.AppendText("\nTY: " + itcontains)
self.textCtrl2.Clear()
pztxtflpath = "TCM/Zoznam.txt"
linenr = 0
with open(pztxtflpath) as f:
found = False
for line in f:
if re.search("\b{0}\b".format(itcontains),line):
hisanswpath = "TCM/" + itcontains + ".txt"
hisansfl = codecs.open(hisanswpath, "r")
textline = hisansfl.readline()
linenr = 0
ans = ""
while textline <> "":
linenr += 1
textline = hisansfl.readline()
hisansfl.close()
rnd = random.randint(1, linenr) - 1
hisansfl = codecs.open(pztxtflpath, "r")
textline = hisansfl.readline()
linenr = 0
pzd = ""
while linenr <> rnd:
textline = hisansfl.readline()
linenr += 1
ans = textline
hisansfl.close()
self.textCtrl.AppendText("\nTexter: " + ans)
if not found:
self.textCtrl.AppendText("\nTexter: " + itcontains)
wrtnw = codecs.open(pztxtflpath, "a")
wrtnw.write("\n" + itcontains)
wrtnw.close
If there is not that string it is working corectly, but if there is that string, what i am searching for it makes if not found action. I really don´t know how to fix it, i have already try some codes from other sites, but in my code it doesn´t works. Can somebody help please?
Are you saying that the code underneath the following if statement executes if the string contains what you're looking for?
if re.search("\b{0}\b".format(itcontains),line):
If so, then you just need to add the following to the code block underneath this statement:
found = True
This will keep your if not found clause from running. If the string you are looking for should only be found once, I would also add a break statement to your first statement to break out of the loop.

How can we strip spaces before writing into csv

! # $ % & ( ) * , - 0 / : < = > ? # [ \ ] ^
this the header of my csv file.. after : you can see one blank space like my csv file header also contain one column with header blank.how can remove by updating following code??
feature_list = ""
root_flag = 'false'
fvt_length = 0
output_file="/home/user/Project/Dataset/unigram_FVT.csv"
feature_vector_file1 = "/home/user/Project/Dataset/BST_unigram.txt"
d = os.path.dirname(output_file)
if not os.path.exists(d):
os.makedirs(d)
with open(output_file, "w" ) as fout:
fp_feature = csv.writer(fout)
fileread=open(feature_vector_file1,"r")
read_list=fileread.read()
read_list=dataPreprocessing.remove_words_less_than_3(read_list)
read_list = read_list.replace('\n','')
read_list = re.sub( '\s+', ' ',read_list).strip()
read_list = dataPreprocessing.remove_digits(read_list)
unigram_list=list(set(read_list.split(" ")))
for i in range(0,len(unigram_list)):
unigram_list[i]=unigram_list[i].lstrip().rstrip()
if root_flag == 'false' :
root = Node(unigram_list[i])
root_flag = 'true'
else :
root.insert(unigram_list[i])
feature_list = feature_list + "\n"+unigram_list[i]
feature_list1 = feature_list.strip()
line = feature_list1.split('\n')
line.sort()
line.append("Gender")
root.print_tree()
print len(line)
fp_feature.writerow(line)
FVT_unigram()
Can anybody can help me? Sometimes my file content contains some spaces but I have added this unigram_list[i]=unigram_list[i].lstrip().rstrip() but still my header contains spaces.
I ran into a similar problem with my program the other day, and I realized the easiest thing to do is ato write a simple if statement and just create a new string/list:
aStr = "Hello World this is a test!"
newStr = ""
for letter in aStr:
if letter!=" ":
newStr += letter
And when I print the newStr:
HelloWorldthisisatest!

Python script couldnt detect mismatch when $instance deleted in only one of the value nvp_add in double if else input statement [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
This is continuation question from stackoverflow question below:
How do I filter nested cases to be filter out python
How to compare the attributes start with $ in 2 functions and display match or mismatch
When i delete one of the $apsChanConfigNumber from nvp_add in first block of if, the compare python script from link above couldn't detect the mismatch, there are 2 nvp_add function under this case. How to resolve the issue help!!!
Input file ASCII plain text contain text below:
if(exists($snmpTrapEnterprise))
{
if(match($OPTION_EnableDetails, "1") or
match($OPTION_EnableDetails_juniper, "1")) {
details($snmpTrapEnterprise,$apsChanStatusSwitchovers,$apsChanStatusCurrent,$apsChanConfigGroupName,$apsChanConfigNumber)
}
#ExtendedAttr = nvp_add(#ExtendedAttr, "snmpTrapEnterprise", $snmpTrapEnterprise, "apsChanStatusSwitchovers", $apsChanStatusSwitchovers, "apsChanStatusCurrent", $apsChanStatusCurrent,
"apsChanConfigGroupName", , "apsChanConfigNumber",)
}
else
{
if(match($OPTION_EnableDetails, "1") or
match($OPTION_EnableDetails_juniper, "1")) {
details($apsChanStatusSwitchovers,$apsChanStatusCurrent,$apsChanConfigGroupName,$apsChanConfigNumber)
}
#ExtendedAttr = nvp_add(#ExtendedAttr, "apsChanStatusSwitchovers",
$apsChanStatusSwitchovers, "apsChanStatusCurrent", $apsChanStatusCurrent,
"apsChanConfigGroupName", $apsChanConfigGroupName,
"apsChanConfigNumber", $apsChanConfigNumber)
}
since ive started, ill finish :P
import re
import sys
from collections import Counter
#sys.stdout = open("result.txt", 'w+')
def intersect(list1, list2):
for o in list1:
if o in list2:
list1.remove(o)
list2.remove(o)
return list1, list2
def read(in_file):
cases = []
caselines_index = []
readlines = []
readlines_num = []
with open(in_file, 'r') as file:
readfile = file.read().strip()
for line in readfile.split('\n'):
readlines_num.append(line.strip())
regex = re.compile("switch\(\$\d\).+?\}", re.DOTALL)
readfile = re.sub(regex, ' ', readfile)
for line in readfile.split('\n'):
readlines.append(line.strip())
for line in readlines:
case_search = re.search("case\s\".+?\"\:\s", line)
if case_search:
caselines_index.append(readlines.index(line))
#print caselines_index
caselines_index_iter = iter(caselines_index)
try:
int_line_index = int(next(caselines_index_iter))
except:
print "No cases found"
try:
int_next_index = int(next(caselines_index_iter))
except:
int_next_index = len(readlines) - 1
while True:
try:
case_text = ' '.join(readlines[int_line_index:int_next_index]).strip()
match1 = re.search("nvp_add", case_text)
match2 = re.search("details", case_text)
if match1 or match2:
case = [readlines[int_line_index].strip(), readlines_num.index(readlines[int_line_index]) + 1, case_text]
cases.append(case)
int_line_index = int_next_index
int_next_index = int(next(caselines_index_iter))
except StopIteration:
case_text = ' '.join(readlines[int_line_index:len(readlines) - 1]).strip()
case = [readlines[int_line_index].strip(), readlines_num.index(readlines[int_line_index]), case_text]
cases.append(case)
break
return cases
def work(cases):
MATCH = 1
for case_list in cases:
details = []
nvp_add = []
caseline = case_list[0].strip()
nvp = re.findall("details\(.+?\)", case_list[2].strip())
for item in nvp:
result_list = re.findall("(\$.+?)[\,\)]", item)
for result in result_list:
if "$*" not in result:
details.append(result)
nvp = re.findall("nvp_add\(.+?\)", case_list[2].strip())
for item in nvp:
result_list = re.findall("(\$.+?)[\,\)]", item)
for result in result_list:
if "$*" not in result:
nvp_add.append(result)
nvp_add_c = Counter(nvp_add)
details_c = Counter(details)
missing_from_details = list((nvp_add_c - details_c).elements())
missing_from_nvp_add = list((details_c - nvp_add_c).elements())
if missing_from_nvp_add or missing_from_details:
MATCH = 0
print caseline + " LINE - " + str(case_list[1] + 1)
for mismatch in missing_from_details:
print "Missing from details:"
print mismatch
for mismatch in missing_from_nvp_add:
print "Missing from nvp_add:"
print mismatch
print "\n"
if MATCH == 1:
print "MATCH"
else:
print "MISMATCHES"
def main():
in_file = "target1.txt"
cases = read(in_file)
work(cases)
if __name__=="__main__":
main()

Categories