Tricks between plain python script and functions? - python

As a very newbie to programming, I tried to test every function individually, make sure it works right.
Here is my problem: for single plainly test, it works; turn it to functions and combine them into a script, them don't work.
For example:
def getRigs (fileObj):
fileObj.seek(0)
rigList = []
Tag = False
for line in fileObj:
if line.find("[BeginRigs]") != -1:
Tag = True
elif line.find("[EndRigs]") != -1:
Tag = False
elif Tag:
rigList.append(line.strip())
return (rigList)
def getObjects (fileObj):
fileObj.seek(0)
objList = []
Tag = False
for line in fileObj:
if line.find("[BeginObjects]") != -1:
Tag = True
elif line.find("[EndObjects]") != -1:
Tag = False
elif Tag:
objList.append(line.strip())
return (objList)
def dummyRig (rigObj, objName):
dummy = ""
for rig in rigObj:
with open(rig, "r") as infile:
#rigObj.seek(0)
Tag = None
for line in infile:
for obj in objName:
if line.find("ObjectAlias " + obj + "\n") !=-1:
Tag = "Mark"
dummy += line
break
elif line.find("BeginKeyframe") != -1:
if Tag == "Mark":
Tag = "Copy"
break
elif line.find("EndKeyframe") != -1:
if Tag == "Copy":
Tag = None
dummy += line
break
if Tag == "Copy":
dummy += line
return (dummy)
def getBlock (rigObj, objName):
Tag = False
block = ""
for line in rigObj:
if line.find("ObjectAlias " + str(objName) + "\n") != -1:
for line in rigObj:
if line.find("BeginKeyframe") != -1:
Tag = True
elif line.lstrip().startswith("0.000 ") and line.rstrip().endswith("default"):
Tag = False
break
elif Tag:
block += line
return (block)
inputconfig = open("config.cfg", "r")
infile = sys.argv[1]
inputscene = open(infile, "r")
outfile = infile.split(".")[0] + "_updated.fxs"
outputscene = open(outfile, "w")
a_rigList = getRigs (inputconfig)
a_objList = getObjects (inputconfig)
a_dummyRig = dummyRig (a_rigList, a_objList)
#print a_dummyRig #----> Output as expected
tmp = getBlock (a_dummyRig, a_objList)
outputscene.write(tmp) #----> Gvie me empty output!
If I test "getBlock" function individually, it works fine:
with open("result_from_a_dummyRig", "r") as rigObj, open("result", "w") as output:
Tag = False
for line in rigObj:
if line.find("ObjectAlias " + "rooster_bn_featherLa_rt_08" + "\n") != -1:
for line in rigObj:
if line.find("BeginKeyframe") != -1:
Tag = True
elif line.lstrip().startswith("0.000 ") and line.rstrip().endswith("default"):
Tag = False
break
elif Tag:
output.write(line)
What am I doing wrong?
EDIT: Add more of my code, hope it helps for the question. The code is design for copy some external data from other files to update my current files.
Thanks bruno, I got your point. The dummyRig function give me a string but not a "real" file. And getBlock function needs a "real" file input. Right?
Still hope someone give me more useful helps, I am not a programmer, I don't know much about python.

In your "test", you are iterating over an opened file. The file iterator iterate over the file's lines.
In your script, what you're passing to getBlock is a string, so you're iterating over the string's individual characters. No surprise you don't get the same results.
If you want getBlock to be able to work on both an opened file OR some arbitray string, you have to wrap the string in some file-like object that will iterate over line, not chars. The stdlib's StringIO module comes to mind...
Also if you really want to be serious about tests, use some automated unittest framework (unittest might not be the most sexy but it's in the stdlib) and make sure you really test the same thing that you will pass to your function ;)

Related

Recalling words from external files and using them as values

So i am trying to read words off of a .txt file to determine the order of functions in my script. It reads the line correctly but does not actually do what it is supposed to. any help would be much appreciated, as I am at a loss for where the problem even starts.
settings_file = open('Settings.txt', 'r')
homescreen_order_string_1 = ['assignments ']
homescreen_order_string_2 = ['checklists ']
homescreen_order_string_3 = ['custom text ']
lines = settings_file.readlines()
lines_to_read_1 = [3]
def readline(lines):
if lines in homescreen_order_string_1:
return "assignments"
elif lines in homescreen_order_string_2:
return "checklists"
elif lines in homescreen_order_string_3:
return "custom text"
else:
return "err"
with open('Settings.txt', 'r') as settings_file:
for position, lines in enumerate(settings_file):
if position in lines_to_read_1:
if readline(lines) == "assignments":
print("yay") #placeholder for function to display assignments
break
elif readline(lines) == "checklists":
print('yay 2') #placeholder for functions to display checklists
break
elif readline(lines) == "custom text":
print("yay3") #placeholder for function to display custom text
break
elif readline(lines) == "err":
print("err")
print(lines) #this is just for bug testing, to see what the system is actualy seeing.
break
else:
pass
#here is the .txt file I am trying to pull from:
#-----------------------------------------
#Settings:
# order of homescreen print:
#assignments
#checklists
#custom text
#
# Custom Text:
#you have no custom text!-
Consider doing this with a dictionary that maps your commands to a function:
settings_file = open('Settings.txt', 'r')
def assignment_handler():
print("yay")
def checklists_handler():
print("yay 2")
def custom_handler():
print("yay 3")
handlers = {
'assignments': assignment_handler,
'checklists': checklists_handler,
'custom text': custom_handler
}
with open('Settings.txt', 'r') as settings_file:
for position, line in enumerate(settings_file):
line = line.strip()
if position in lines_to_read_1:
if line in handlers:
handlers[line]()
else:
print( "Unknown choice", line )

cloze solver not working

I have been using python for some time, I have a file that is the english alphabet with each word on separate lines, and I have ironed out all the errors, but it doesn't type anything anymore. I'm open to any help, and improvements to the code, provided you explain how it works. If you are looking for the file it is here
f = open("C:\\my folders\\brit-a-z.txt", 'r')
print("Type in your cloze word like this: cl-z-")
def cloze(word):
for line in f:
match = True
if len(line) == len(word):
for i in range(len(word)):
if not word[i] == "-":
if line[i] == word[i]:
match == False
if match == True:
print(line)
while True:
cloze(input())
Once you've iterated through the file for the first word, the file closes. You'll need to save f. For example:
with open("C:\\my folders\\brit-a-z.txt", 'r') as f:
f = f.read().splitlines()

How to search a string in JS file (multiple lines) in python? [duplicate]

I want to check if a string is in a text file. If it is, do X. If it's not, do Y. However, this code always returns True for some reason. Can anyone see what is wrong?
def check():
datafile = file('example.txt')
found = False
for line in datafile:
if blabla in line:
found = True
break
check()
if True:
print "true"
else:
print "false"
The reason why you always got True has already been given, so I'll just offer another suggestion:
If your file is not too large, you can read it into a string, and just use that (easier and often faster than reading and checking line per line):
with open('example.txt') as f:
if 'blabla' in f.read():
print("true")
Another trick: you can alleviate the possible memory problems by using mmap.mmap() to create a "string-like" object that uses the underlying file (instead of reading the whole file in memory):
import mmap
with open('example.txt') as f:
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if s.find('blabla') != -1:
print('true')
NOTE: in python 3, mmaps behave like bytearray objects rather than strings, so the subsequence you look for with find() has to be a bytes object rather than a string as well, eg. s.find(b'blabla'):
#!/usr/bin/env python3
import mmap
with open('example.txt', 'rb', 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
if s.find(b'blabla') != -1:
print('true')
You could also use regular expressions on mmap e.g., case-insensitive search: if re.search(br'(?i)blabla', s):
As Jeffrey Said, you are not checking the value of check(). In addition, your check() function is not returning anything. Note the difference:
def check():
with open('example.txt') as f:
datafile = f.readlines()
found = False # This isn't really necessary
for line in datafile:
if blabla in line:
# found = True # Not necessary
return True
return False # Because you finished the search without finding
Then you can test the output of check():
if check():
print('True')
else:
print('False')
Here's another way to possibly answer your question using the find function which gives you a literal numerical value of where something truly is
open('file', 'r').read().find('')
in find write the word you want to find
and 'file' stands for your file name
if True:
print "true"
This always happens because True is always True.
You want something like this:
if check():
print "true"
else:
print "false"
Good luck!
I made a little function for this purpose. It searches for a word in the input file and then adds it to the output file.
def searcher(outf, inf, string):
with open(outf, 'a') as f1:
if string in open(inf).read():
f1.write(string)
outf is the output file
inf is the input file
string is of course, the desired string that you wish to find and add to outf.
Your check function should return the found boolean and use that to determine what to print.
def check():
datafile = file('example.txt')
found = False
for line in datafile:
if blabla in line:
found = True
break
return found
found = check()
if found:
print "true"
else:
print "false"
the second block could also be condensed to:
if check():
print "true"
else:
print "false"
Two problems:
Your function does not return anything; a function that does not explicitly return anything returns None (which is falsy)
True is always True - you are not checking the result of your function
.
def check(fname, txt):
with open(fname) as dataf:
return any(txt in line for line in dataf)
if check('example.txt', 'blabla'):
print "true"
else:
print "false"
How to search the text in the file and Returns an file path in which the word is found
(Как искать часть текста в файле и возвращять путь к файлу в котором это слово найдено)
import os
import re
class Searcher:
def __init__(self, path, query):
self.path = path
if self.path[-1] != '/':
self.path += '/'
self.path = self.path.replace('/', '\\')
self.query = query
self.searched = {}
def find(self):
for root, dirs, files in os.walk( self.path ):
for file in files:
if re.match(r'.*?\.txt$', file) is not None:
if root[-1] != '\\':
root += '\\'
f = open(root + file, 'rt')
txt = f.read()
f.close()
count = len( re.findall( self.query, txt ) )
if count > 0:
self.searched[root + file] = count
def getResults(self):
return self.searched
In Main()
# -*- coding: UTF-8 -*-
import sys
from search import Searcher
path = 'c:\\temp\\'
search = 'search string'
if __name__ == '__main__':
if len(sys.argv) == 3:
# создаем объект поисковика и передаем ему аргументы
Search = Searcher(sys.argv[1], sys.argv[2])
else:
Search = Searcher(path, search)
# начать поиск
Search.find()
# получаем результат
results = Search.getResults()
# выводим результат
print 'Found ', len(results), ' files:'
for file, count in results.items():
print 'File: ', file, ' Found entries:' , count
If user wants to search for the word in given text file.
fopen = open('logfile.txt',mode='r+')
fread = fopen.readlines()
x = input("Enter the search string: ")
for line in fread:
if x in line:
print(line)
found = False
def check():
datafile = file('example.txt')
for line in datafile:
if blabla in line:
found = True
break
return found
if check():
print "true"
else:
print "false"
found = False
def check():
datafile = file('example.txt')
for line in datafile:
if "blabla" in line:
found = True
break
return found
if check():
print "found"
else:
print "not found"
Here's another. Takes an absolute file path and a given string and passes it to word_find(), uses readlines() method on the given file within the enumerate() method which gives an iterable count as it traverses line by line, in the end giving you the line with the matching string, plus the given line number. Cheers.
def word_find(file, word):
with open(file, 'r') as target_file:
for num, line in enumerate(target_file.readlines(), 1):
if str(word) in line:
print(f'<Line {num}> {line}')
else:
print(f'> {word} not found.')
if __name__ == '__main__':
file_to_process = '/path/to/file'
string_to_find = input()
word_find(file_to_process, string_to_find)
"found" needs to be created as global variable in the function as "if else" statement is out of the function. You also don't need to use "break" to break the loop code.
The following should work to find out if the text file has desired string.
with open('text_text.txt') as f:
datafile = f.readlines()
def check():
global found
found = False
for line in datafile:
if 'the' in line:
found = True
check()
if found == True:
print("True")
else:
print("False")

Error in python search function

I am getting trying to build a search function which searches through text files and prints the search string if the string is found in the text file. If the users second string (quotesearch2) is empty then only the first string is searched and printed (quotesearch1). Why do i keep getting 2 syntax error messages for lines 16 and line 23 (the code checker stoped after line 105 so there may be more after this point).excuse the code, i am only a beginner, I do not want alternative code to complete the function, i just want the errors resolved.
The error is:
SyntaxError: invalid syntax
def search():
import os.path
print "you chose the search option"
validchars = "-.() %s%s" %(string.ascii_letters , string.digits)
thisDir = raw_input("What directory would you like to search ? Not: Any invalid characters will be stripped ") #ask user to choose a directory for multi OS compatibility
thisDir = ''.join(y for y in filesearch if y in validchars)
filesearch = raw_input("What file would you like to search ? Note: Any invalid characters will be stripped: ") #ask user what file they would like t search from
filesearch = ''.join(x for x in filesearch if x in validchars)
fullpath = os.path.join(thisDir, filesearch) #create full path for all operating system compatibility
while os.path.isfile(fullpath) == false: #check if the file doesnt exist, if it doesnt alert the user
print "sorry the file you chose does not exist"
thisDir = pickAFolder
filesearch = raw_input("What file would you like to search ? Note: Any invalid characters will be stripped: ")
filesearch = ''.join(x for x in filesearch if x in validchars) #strip invalid characters
fullpath = os.path.join(thisDir, filesearch)
elif os.path.isfile(fullpath) == true:
f = open(fullpath, 'r') #open file
found = false
linecount = 0
while found == false: # while the found variable is equal to false ask the user what they would like to search
quotesearch1 = raw_input("whats the first string you would you like to search ?: ")
quotesearch2 = raw_input("whats the second string you want to search for ?: "
for line in f: #for each line in the quote file if the quotesearch1 (usersfirst search) is in the line, print it along with a blank line
if quotesearch2 != " " or "":
if quotesearch1 and quotesearch2 in line:
print line
print "\n"
linecount = line + 1 # variable to track the amount of lines printed
elif quotesearch2 == " " or "":
if quotesearch1 in line:
print line
print "\n"
linecount = line + 1
found = true
if linecount == 0 and found == true : # if variable == 0 the quote search was not in the file and if the search was completed
print "sorry the search could not be found" # print the quote search cold not be found
Menu = true
fclose(fullpath)
elif found == true:
print "search complete"
while os.path.isfile(fullpath) == false:
elif os.path.isfile(fullpath) == true:
You use capital F for False in Python and capital T for True
And you are missing a closing ")" on the line quotesearch2 = raw_input("whats the second string you want to search for ?: "
if quotesearch2 != " " or "":
should be if quotesearch2 != " " or quotesearch2 != "":
elif quotesearch2 == " " or "":
should be elif quotesearch2 == " " or quotesearch2 == "":
You are not checking if quotesearch2 is not equal to ""
In [7]: i=10
In [8]: if i == 9 or 4:
print "weird"
...:
weird
In [9]: if i == 9 or i == 4:
print "weird"
...:
In [10]:
You see you the print "weird" gets executed even though i is not equal to 10 but in the second statement when I use or i == 4: it does not.

How to search for a string in text files?

I want to check if a string is in a text file. If it is, do X. If it's not, do Y. However, this code always returns True for some reason. Can anyone see what is wrong?
def check():
datafile = file('example.txt')
found = False
for line in datafile:
if blabla in line:
found = True
break
check()
if True:
print "true"
else:
print "false"
The reason why you always got True has already been given, so I'll just offer another suggestion:
If your file is not too large, you can read it into a string, and just use that (easier and often faster than reading and checking line per line):
with open('example.txt') as f:
if 'blabla' in f.read():
print("true")
Another trick: you can alleviate the possible memory problems by using mmap.mmap() to create a "string-like" object that uses the underlying file (instead of reading the whole file in memory):
import mmap
with open('example.txt') as f:
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if s.find('blabla') != -1:
print('true')
NOTE: in python 3, mmaps behave like bytearray objects rather than strings, so the subsequence you look for with find() has to be a bytes object rather than a string as well, eg. s.find(b'blabla'):
#!/usr/bin/env python3
import mmap
with open('example.txt', 'rb', 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
if s.find(b'blabla') != -1:
print('true')
You could also use regular expressions on mmap e.g., case-insensitive search: if re.search(br'(?i)blabla', s):
As Jeffrey Said, you are not checking the value of check(). In addition, your check() function is not returning anything. Note the difference:
def check():
with open('example.txt') as f:
datafile = f.readlines()
found = False # This isn't really necessary
for line in datafile:
if blabla in line:
# found = True # Not necessary
return True
return False # Because you finished the search without finding
Then you can test the output of check():
if check():
print('True')
else:
print('False')
Here's another way to possibly answer your question using the find function which gives you a literal numerical value of where something truly is
open('file', 'r').read().find('')
in find write the word you want to find
and 'file' stands for your file name
if True:
print "true"
This always happens because True is always True.
You want something like this:
if check():
print "true"
else:
print "false"
Good luck!
I made a little function for this purpose. It searches for a word in the input file and then adds it to the output file.
def searcher(outf, inf, string):
with open(outf, 'a') as f1:
if string in open(inf).read():
f1.write(string)
outf is the output file
inf is the input file
string is of course, the desired string that you wish to find and add to outf.
Your check function should return the found boolean and use that to determine what to print.
def check():
datafile = file('example.txt')
found = False
for line in datafile:
if blabla in line:
found = True
break
return found
found = check()
if found:
print "true"
else:
print "false"
the second block could also be condensed to:
if check():
print "true"
else:
print "false"
Two problems:
Your function does not return anything; a function that does not explicitly return anything returns None (which is falsy)
True is always True - you are not checking the result of your function
.
def check(fname, txt):
with open(fname) as dataf:
return any(txt in line for line in dataf)
if check('example.txt', 'blabla'):
print "true"
else:
print "false"
How to search the text in the file and Returns an file path in which the word is found
(Как искать часть текста в файле и возвращять путь к файлу в котором это слово найдено)
import os
import re
class Searcher:
def __init__(self, path, query):
self.path = path
if self.path[-1] != '/':
self.path += '/'
self.path = self.path.replace('/', '\\')
self.query = query
self.searched = {}
def find(self):
for root, dirs, files in os.walk( self.path ):
for file in files:
if re.match(r'.*?\.txt$', file) is not None:
if root[-1] != '\\':
root += '\\'
f = open(root + file, 'rt')
txt = f.read()
f.close()
count = len( re.findall( self.query, txt ) )
if count > 0:
self.searched[root + file] = count
def getResults(self):
return self.searched
In Main()
# -*- coding: UTF-8 -*-
import sys
from search import Searcher
path = 'c:\\temp\\'
search = 'search string'
if __name__ == '__main__':
if len(sys.argv) == 3:
# создаем объект поисковика и передаем ему аргументы
Search = Searcher(sys.argv[1], sys.argv[2])
else:
Search = Searcher(path, search)
# начать поиск
Search.find()
# получаем результат
results = Search.getResults()
# выводим результат
print 'Found ', len(results), ' files:'
for file, count in results.items():
print 'File: ', file, ' Found entries:' , count
If user wants to search for the word in given text file.
fopen = open('logfile.txt',mode='r+')
fread = fopen.readlines()
x = input("Enter the search string: ")
for line in fread:
if x in line:
print(line)
found = False
def check():
datafile = file('example.txt')
for line in datafile:
if blabla in line:
found = True
break
return found
if check():
print "true"
else:
print "false"
found = False
def check():
datafile = file('example.txt')
for line in datafile:
if "blabla" in line:
found = True
break
return found
if check():
print "found"
else:
print "not found"
Here's another. Takes an absolute file path and a given string and passes it to word_find(), uses readlines() method on the given file within the enumerate() method which gives an iterable count as it traverses line by line, in the end giving you the line with the matching string, plus the given line number. Cheers.
def word_find(file, word):
with open(file, 'r') as target_file:
for num, line in enumerate(target_file.readlines(), 1):
if str(word) in line:
print(f'<Line {num}> {line}')
else:
print(f'> {word} not found.')
if __name__ == '__main__':
file_to_process = '/path/to/file'
string_to_find = input()
word_find(file_to_process, string_to_find)
"found" needs to be created as global variable in the function as "if else" statement is out of the function. You also don't need to use "break" to break the loop code.
The following should work to find out if the text file has desired string.
with open('text_text.txt') as f:
datafile = f.readlines()
def check():
global found
found = False
for line in datafile:
if 'the' in line:
found = True
check()
if found == True:
print("True")
else:
print("False")

Categories