string comparison failing in python? - python

I have a small script which goes like this:
(Notice the comparison)
def readVariations(path_to_source_config):
varsTuple = []
source_file = open(path_to_source_config, "r")
for line in source_file:
line_no_spaces = line.replace(" ","")
if line_no_spaces[0] == '[':
current_line_ = line_no_spaces.replace("[", "")
current_line = current_line_.replace("]", "")
section = "ExecutionOptimizer"
if current_line == section:
print current_line
#_tuple = section_name, option_name, range_start, range_end, step
#varsTuple.append(_tuple)
return varsTuple
What it does is reads a config file (.cfg) and needs to check if it finds a particular string.
The following line comes up in the config file:
[ExecutionOptimizer]
For some reason the comparison is failing when the same string is encountered in the file.
Can you please tell me why.

I suspect line ends with a newline character, and it remains there throughout all of your replace operations. Then your comparison fails because "ExecutionOptimizer\n" doesn't equal "ExecutionOptimizer". You can discard the newline using strip:
line_no_spaces = line.strip().replace(" ","")

Use "is" key word.
"==" is for equality testing
From a Python interpreter:
> a = 'tea'
> b = ''.join(['t', 'e', 'a'])
> a == b
True
> a is b
False

Related

Can I find a line in a text file, if I know its number in python?

word = "some string"
file1 = open("songs.txt", "r")
flag = 0
index = 0
for line in file1:
index += 1
if word in line:
flag = 1
break
if flag == 0:
print(word + " not found")
else:
#I would like to print not only the line that has the string, but also the previous and next lines
print(?)
print(line)
print(?)
file1.close()
Use contents = file1.readlines() which converts the file into a list.
Then, loop through contents and if word is found, you can print contents[i], contents[i-1], contents[i+1]. Make sure to add some error handling if word is in the first line as contents[i-1] would throw and error.
word = "some string"
file1 = open("songs.txt", "r")
flag = 0
index = 0
previousline = ''
nextline = ''
for line in file1:
index += 1
if word in line:
finalindex = index
finalline = line
flag = 1
elsif flag==1
print(previousline + finalline + line)
print(index-1 + index + index+1)
else
previousline = line
You basically already had the main ingredients:
you have line (the line you currently evaluate)
you have the index (index)
the todo thus becomes storing the previous and next line in some variable and then printing the results.
have not tested it but code should be something like the above.....
splitting if you find the word, if you have found it and you flagged it previous time and if you have not flagged it.
i believe the else-if shouldnt fire unless flag ==1

Read Lines Depending on Value in Following Lines

I am trying to do a calculation based on the content of a line, but only if another line in the same document satisfies specific criteria. The order of the lines is not consistent.
A file might look like this:
Line A: 200
Line B: 200
Line C: 5
So an example condition would be, if Line C is 6 or greater, add the value from Line A "200" to a counter.
I have tried a variety of if statements, and also tried setting a BOOL. I haven't been able to get either to work. An excerpt of my latest attempt follows:
counter = 0
good = True
for line in text:
line = line.strip()
if line.startswith('Line C') :
rtime = re.findall('[0-9]+:[0-9]+', line)
for t in rtime:
if t < 6 :
good = False
print("-----To Small. Ignore Line A")
break
else :
good = True
while good == True :
if line.startswith('Line A') :
numstring = re.findall('[0-9]+', line)
for num in numstring:
temp = float(num)
counter = counter + temp
else : continue
print("----- good must be False. Should be ignoring Line A")
First, read all the rows from the file into a dictionary so that you have:
{'Line A':200, 'Line B':200, 'Line C':5}
After this it is easy to apply the criterias with conditionals like "if value['Line A'] > 6:" etc.
I am leaving with you the implementation of this because it sounds a bit homework-y. Let me know if you need more help!
Maybe you can use a dictionary if the lines aren't too long. A simple way would just add the lines to a dictionary and then check your condition.
import re
allDataLines = []
allQualifierLines = []
dataFileName = 'testdata.txt'
def chckForQualifierLine(line):
# lines containing qualifier
if not line.startswith('Line C'):
return False
# do more checks here, if not good just return False
allQualifierLines.append(line)
return True
def chckForDataLine(line):
# lines containing data
if not line.startswith('Line A'):
return False
# do more checks here, if not good just return False
allDataLines.append(line)
return True
with open(dataFileName, 'r') as text:
# Further file processing goes here
line = text.readline()
while line != '':
#print(line, end='')
if not chckForQualifierLine(line):
chckForDataLine(line)
line = text.readline()
for qualifierLine in allQualifierLines:
# this line is valid qualifier
print(f"Q: {qualifierLine}")
for dataLine in allDataLines:
# do with data line(s) what ever is to do here
print(f"D: {dataLine}")

How do I print words in a specific alphabetical range coming from lines in a file?

So I have to write a code that first reads in the name of an input file, followed by two strings representing the lower and upper bounds of a search range. The file should be read using the file.readlines() method. The input file contains a list of alphabetical, ten-letter strings, each on a separate line. The program should output all strings from the list that are within that range (inclusive of the bounds).
The text file (input1.txt) contains:
aspiration
classified
federation
graduation
millennium
philosophy
quadratics
transcript
wilderness
zoologists
so for example, if i input:
input1.txt
ammoniated
millennium
the output should be:
aspiration
classified
federation
graduation
millennium
So far, I tried:
# prompt user to enter input1.txt as filepath
filepath = input()
start = input()
end = input()
apending = False
out = ""
with open(filepath) as fp:
line = fp.readline()
while line:
txt = line.strip()
if(txt == end):
apending = False
# how do I make it terminate after end is printed??
if(apending):
out+=txt + '\n'
if(txt == start):
apending = True
line = fp.readline()
print(out)
However, it does not seem to output anything. Any help debugging or fixing my code is greatly appreciated~
here is the code:
# prompt user to enter input1.txt as filepath
filepath = input()
start = input()
end = input()
# apending = False
# out = ""
with open(filepath) as fp:
while True:
line = fp.readline()
if not line:
break
txt = line.strip()
if txt >= start and txt <= end:
print(txt)
if txt > end:
break
None of the strings in the input is equal to ammoniated, therefore txt == start is never true, therefore apending is never set to True, therefore out += txt + '\n' is never executed, therefore print(out) prints an empty string at the end.
You should use < or > to compare the strings from the input with start and end. They are not supposed to be exact matches.
This can be done by comparing strings using the <= and >= operators, and then filtering the words that match the lower and upper bounds criteria.
As said in this article, "Python string comparison is performed using the characters in both strings. The characters in both strings are compared one by one. When different characters are found then their Unicode value is compared. The character with lower Unicode value is considered to be smaller."
f = open('input.txt')
words = f.readlines()
lower_bound = input('Set the lower bound for query')
upper_bound = input('Set the upper bound for query')
result = [word.strip() for word in words if lower_bound <= word.strip() <= upper_bound]
print(result)
f.close()
output for print(result), with the input you provided:
['aspiration', 'classified', 'federation', 'graduation', 'millennium']
You can exit out of a for loop by using the keyword break
for example
for x in range(50):
if x > 20:
break;
else:
print(x);

anagram solver not working

So, this has been my project for a long time, and eventually, I have made an anagram solver in python 3.4, except it's supposed to find anagram for the word + a random letter. I have worked out all the error messages, but there are no more errors, it just doesn't do it. All help appreciated. I have had a lot of helpful comments, but it is still not working. I have updated the code in the question.(Here is the file I used with all the words of the dictionary on different lines, it's really helpful and I had to look for something like this for months.)
file = open("C:\\my stuff\\brit-a-z.txt","r")
def anagram(word):
for alpha in range(ord('a'), ord('z') + 1):
newletter = chr(alpha)
for line in file:
ref = line.strip()
word1 = list(word)
list.append(newletter)
word1_list.sort()
ref_list = list(line)
ref_list.sort()
if word1_list == ref_list:
print(line)
while True:
inp = input()
anagram(inp)
.
This should do what you need.
with open("C:\\my_folders_are_in_here\\brit-a-z.txt", 'r') as f:
check_list = [x.strip() for x in f.readlines()]
def anagram(word):
for alpha in range(ord('a'), ord('z') + 1):
newletter = chr(alpha)
for line in check_list:
word1_list = list(word + newletter)
word1_list.sort()
ref_list = list(line)
ref_list.sort()
if word1_list == ref_list:
print(line)
while True:
inp = input()
anagram(inp)
I took advantage of the chr() and ord() built-in function to remove the long if that converts alpha into newletter.
Reading lines from file in Python also includes newline characters.
So if one line in the file is the word "the" for example, assigning ref = line, ref will equal "the\n"(or "the\r\n"). Your sorted ref_list then becomes ['\n', 'e', 'h', 't']
Reading from keyboard using input(), however, does not include newline characters. Your word1_list never contains a '\n', thus, word1_list and ref_list will never be equal.
Fix: change ref = line into ref = line.strip() to remove newline characters.

Equality of Strings in Python

I have this code:
afile = "name.txt"
f = open(afile,"r")
content = f.readlines()
f.close()
correct = content[1]
answer = raw_input()
if answer == correct:
print 'True'
Let say that, because of the name.txt, content[1] is George and then I run the code and I type George for answer.
Why I won't get True?
Why answer and correct are not the same?
The data you read includes newlines; strip those from the lines first:
if answer == correct.strip():
which removes all whitespace from the start and end of a string. If whitespace at the start or end is important, you can remove just newlines from the end with:
if answer == correct.rstrip('\n'):
Rewritten a bit:
def get_file_line(fname, line_num):
with open(fname) as inf:
try:
for _ in range(line_num + 1):
line = inf.next()
return line.rstrip('\r\n')
except StopIteration:
return None
if answer == get_file_line('name.txt', 1):
print('True')

Categories

Resources