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.
Related
I'm learning python so I am pretty new to it.
I've been working on a class assignment and iv'e been facing some error, such as the one in the title.
This is my code:
import random
def getWORDS(filename):
f = open(filename, 'r')
templist = []
for line in f:
templist.append(line.split("\n"))
return tuple(templist)
articles = getWORDS("articles.txt")
nouns = getWORDS("nouns.txt")
verbs = getWORDS("verbs.txt")
prepositions = getWORDS("prepositions.txt")
def sentence():
return nounphrase() + " " + verbphrase()
def nounphrase():
return random.choice(articles) + " " + random.choice(nouns)
def verbphrase():
return random.choice(verbs) + " " + nounphrase() + " " + \
prepositionalphrase()
def prepositionalphrase():
return random.choice(prepositions) + " " + nounphrase()
def main():
number = int(input("enter the number of sentences: "))
for count in range(number):
print(sentence())
main()
However, whenever I run it I get an this error:
TypeError: can only concatenate list (not "str") to list.
Now, I know there are tons of question like this but I tried a lot of time, I am not able to fix it, I'm new to programming so I've been learning the basics since last week.
Thank you
Here I've modified the function slightly - it'll fetch every words into a tuple. Use with to open the files - it will close the pointer once the values have been fetched.
I hope this will work for you!
def getWORDS(filename):
result = []
with open(filename) as f:
file = f.read()
texts = file.splitlines()
for line in texts:
result.append(line)
return tuple(result)
I think the problem is in this line:
templist.append(line.split("\n"))
split() will return a list that is then appended to templist. If you're wanting to remove the newline character from the end of the line use rstrip() as this will return a string.
When working with a file, you should use the read() method:
file = f.read()
To split the file to lines and add to a list, you first split, then append line by line.
file = f.read()
lines = file.split("\n")
for line in lines:
templist.append(line)
In your case, you are using the list of lines as-is, so I would write:
file = f.read()
templist = file.split("\n")
Edit 1:
Another useful tool when working with files is f.readline(), which returns the first line when calling it for the first time, second when calling it once again... third... and so on, although the previous ways I showed would be more efficient here.
Edit 2:
When you are done using the file, use the close() method, or start using the file with a with ... as method which closes the file at the end of the code block.
Code example using with ... as (The best written code in this answer):
def getWORDS(filename):
with open(filename, 'r') as f:
file = f.read()
templist = file.split("\n")
return tuple(templist)
Code example using close():
def getWORDS(filename):
f = open(filename, 'r')
file = f.read()
templist = file.split("\n")
f.close()
return tuple(templist)
This is how I would write the full code.
(fixed file opening and reading + fixed capitalization)
import random
def getWORDS(filename):
with open(filename, 'r') as f:
file = f.read()
templist = file.split("\n")
return tuple(templist)
articles = getWORDS("articles.txt")
nouns = getWORDS("nouns.txt")
verbs = getWORDS("verbs.txt")
prepositions = getWORDS("prepositions.txt")
def sentence():
sentence = nounphrase() + " " + verbphrase()
sentence = sentence.split(" ")
sentence[0] = sentence[0].capitalize()
sentence = " ".join(sentence)
return sentence
def nounphrase():
return random.choice(articles).lower() + " " + random.choice(nouns).capitalize()
def verbphrase():
return random.choice(verbs).lower() + " " + nounphrase() + " " + \
prepositionalphrase()
def prepositionalphrase():
return random.choice(prepositions).lower() + " " + nounphrase()
def main():
number = int(input("enter the number of sentences: "))
for count in range(number):
print(sentence())
main()
I have this large script ( I will post the whole thing if I have to but it is very big) which starts off okay when I run it but it immediatly gives me 'TypeError: cannot concatenate 'str' and 'NoneType' objects' when it comes to this last bit of the code:
with open("self.txt", "a+") as f:
f = open("self.txt", "a+")
text = f.readlines()
text_model = markovify.Text(text)
for i in range(1):
tool = grammar_check.LanguageTool('en-GB')
lin = (text_model.make_sentence(tries=800))
word = ('' + lin)
matches = tool.check (word)
correct = grammar_check.correct (word, matches)
print ">",
print correct
print ' '
f = open("self.txt", "a+")
f.write(correct + "\n")
I have searched everywhere but gotten nowhere. It seems to have something to do with: word = ('' + lin). but no matter what I do I can't fix it. What am I doing wrong?
I'm not sure how I did it but with a bit of fiddling and google I came up with a solution, the corrected code is here (if you're interested):
with open("self.txt", "a+") as f:
f = open("self.txt", "a+")
text = f.readlines()
text_model = markovify.Text(text)
for i in range(1):
tool = grammar_check.LanguageTool ('en-GB')
lin = (text_model.make_sentence(tries=200))
matches = tool.check (lin)
correct = grammar_check.correct (lin, matches)
lowcor = (correct.lower())
print ">",
print str (lowcor)
print ' '
f = open("self.txt", "a+")
f.write(lowcor + "\n")
Thanks for all the replies, they had me thinking and that's how I fixed it!
You can't concatenate a string and a NoneType object. In your code, it appears your variable lin is not getting assigned the value you think it is. You might try an if block that starts like this:
if type(lin) == str:
some code
else:
raise Exception('lin is not the correct datatype')
to verify that lin is the correct datatype before printing.
Here is my function. Trying to get this all to print to one line.
Here is the output ->
config::$var['pdf']['meta']['staff_member_name']
= ";"
The = ";" portion of the string prints to a new line in the console for some reason?
This is totally just a personal hack to help with a repetitious job requirement so i'm not looking for anything fancy.
Here is my function ->
def auto_pdf_config(file):
with open(file) as f:
content = f.readlines()
kill = " = array("
start = "config::$var['intake']"
new_line = ""
for line in content:
if kill not in line:
pass
elif start in line:
new_line = line
x = new_line.replace(kill, "")
y = x.replace(start,"")
pdf_end = ' = ";" '
z = "config::$var['pdf']['meta']{}{}".format(y,pdf_end)
print(z)
it seems you "y" variable has new line in it. you can try to strip it off.
y = x.replace(start,"").strip('\n')
Since x = new_line.replace(kill, ""), y = x.replace(start,""), and new_line is the line of content, it contains endline symbol (\n), that's why this endline symbol is appended before pdf_end. You just need to remove endline symbol from y.
You can do something like that:
y = y.strip('\n')
! # $ % & ( ) * , - 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!
I am a little new to python and I am trying to write this script to cancel print jobs over 1 mb.. (the line where it is checking for size is set to 1 mb just to make sure it is working). for some reason my last else statement keeps saying it has invalid syntax. I checked to see if all parentheses were closed and I could not find an unmatched pair. could someone please tell me why it says it is invalid? Also can you take a look at my line 24 (fullname = ...grep...) to make sure the syntax on that is correct?
#! /usr/bin/python
import os
infile = open ('test.pl', 'r')
outfile = open('print.reportpython', 'w+')
newfile = infile.readlines()
newfile.pop(0)
count = 0
firstline = newfile[0]
splitline = firstline.split()
currentuser = splitline[1]
currentuser = str(currentuser)
for line in newfile:
newline = line.split()
names = newline[1]
size = int(newline[2])
names = str(names)
print names
if names is currentuser:
if size >= 1:
os.popen ("cancel lab01-10292")
fullname = os.popen("cat /etc/passwd |grep " + newline[1] + "cut -d':' -f5")
count += 1
print count
else:
print outfile.write ("(" + currentuser + ")")
print outfile.write (" ")
count = 0
currentuser = names
You do:
if foo:
bar
baz
else:
bomb
Which is wrong. All the lines between the if and its corresponding else must be indented deeper than the if and else, like this:
if foo:
bar
baz
else:
bomb
The else is at the same indentation as the previous line, but the statement on the previous line doesn't have an else clause. Fix your indentation.