Django python escape \n characters - python

In the following function, i upload a file from a template and pass it to the following function.But the data gets crippled if there is a \n or \t(This is a tab separated file).
1.If there is a \n or some special characters it stores the data in the next row.How to avoid this .
2.data is not None or data != "" still stores a null value
def save_csv(csv_file,cnt):
ret = 1
arr = []
try:
flag = 0
f = open(csv_file)
for l in f:
if flag == 0:
flag += 1
continue
parts = l.split("\t")
counter = 1
if(len(parts) > 6):
ret = 2
else:
taggeddata = Taggeddata()
for data in parts:
data = str(data.strip())
if counter == 1 and (data is not None or data != ""):
taggeddata.field1 = data
elif counter == 2 and (data is not None or data != ""):
taggeddata.field2 = data
elif counter == 3 and (data is not None or data != ""):
taggeddata.field3 = data
elif counter == 4 and (data is not None or data != ""):
taggeddata.field4 = data
elif counter == 5 and (data is not None or data != ""):
taggeddata.field5 = data
elif counter == 6 and (data is not None or data != ""):
taggeddata.field6 = data
counter += 1
taggeddata.content_id = cnt.id
taggeddata.save()
arr.append(taggeddata)
return ret
except:
write_exception("Error while processing data and storing")

Use the stdlib's csv module to parse your text, it will be much better at it.
Your expression data is not None or data != "" is always true, you meant data is not None and data != "". Note that you can simplify this to just elif counter == 3 and data:

Related

How to set variable value to be a new row python

My code:
test_str = '''
(()(code)())
((t(e(x(t(()
()(co)de)('''
countofrightbrackets = 0
countofleftbrackets = 0
blockcount = 0
myDict = {};
for i in test_str:
if i == '(':
countofrightbrackets = countofrightbrackets + 1
if i == ')':
countofleftbrackets = countofleftbrackets + 1
if i == '':
blockcount = blockcount + 1
if countofrightbrackets == countofleftbrackets:
myDict.update({blockcount:'True'});
else:
myDict.update({blockcount:'False'});
print (myDict)
My program is counting () and if count of ( = ) then save to dictionary True. Else false. In test_str I have some blocks - they are dissociated with 2 new rows. In if i == '': I want to show, that if I = 2 new rows, then compete the code. Also I need to check are brackets are at correct positions - like ()()() is true and ())( is false. How to do this?
Example:
Input:
(()()())
((((((()
()())(
Output:
1: True 2: False 3: False

TypeError with String indices using integers with Python

This is my code for a programming problem in a CS course that involves tokenizing a string by its opening and closing parentheses.
def expand(S):
if "(" in S:
open, close = parentheses_pair(S)
open = int(int(open) + int(1))
samp = S[open, close]
currstr = samp
innerstr = ""
if "(" in samp:
open, close = parentheses_pair(S)
currstr = samp[:open]
innerstr = samp[open, close+1]
innerstr = expand(innerstr)
output = ""
for i in range(1, len(currstr), 2):
letter = currstr[i-1]
number = currstr[i]
output += letter*number
output += innerstr
sorted_out = sorted(output)
output = "".join(sorted_out)
return output
else:
return ""
def parentheses_pair(S):
counter = 0
openpar = S.find("(")
currind = S.find("(")
found = False
while not found:
if S[currind] == "(":
counter += 1
elif S[currind] == ")":
if counter == 1:
found = True
break
else:
counter -= 1
currind += 1
return int(openpar), int(currind)
When I used type on both open and close, <class 'int'> was returned by the terminal so I really don't know why it won't accept the variables as the string indices on samp = S[open, close].

How to convert For loop into a While loop

def file_read ():
dictionary = {}
state = ""
capital = ""
flag = 0
with open("state_capitals.txt","r") as f:
for line in f:
if flag == 0:
state = line.rstrip('\n')
flag = 1
elif flag == 1:
capital = line.rstrip('\n')
flag = 0
dictionary[state] = capital
print(dictionary)
How would I use a while loop to make the dictionary instead of the for loop. Code works perfectly fine but professor insists I use a while loop.
def file_read():
dictionary = {}
state = ""
capital = ""
flag = 0
with open("state_capitals.txt", "r") as f:
while True:
line = f.readline()
if not line:
break
if flag == 0:
state = line.rstrip('\n')
flag = 1
elif flag == 1:
capital = line.rstrip('\n')
flag = 0
dictionary[state] = capital
print(dictionary)

CS50 DNA - it works for small.csv but not for large

https://cs50.harvard.edu/x/2020/psets/6/dna/#:~:text=python%20dna.py%20databases/large.csv%20sequences/5.txt
I'm trying to solve this problem from CS50 but it just works for the small database, when I try it for the large one the program overcounts.
import csv
if len(argv) != 3:
print("DIGITA DIREITO, IMBECIL")
exit()
with open(argv[1], "r") as source:
reader = list(csv.reader(source))
reader[0].remove("name")
i = reader[0]
with open(argv[2], "r") as sequence:
seq = sequence.read()
values = []
for j in range(len(i)):
value = 0
counter = 0
pos = 0
prevpos = 0
while pos < len(seq):
pos = seq.find(i[j], pos)
if pos == -1:
counter = 0
break
elif (pos != 1):
counter += 1
prevpos = pos
pos += len(i[j])
if value < counter:
value = counter
values.append(value)
for row in range(len(reader)):
print(reader[row])
print(values)
values = list(map(str, values))
search = list(reader)
search.pop(0)
for result in search:
if result[1:] == values:
print(f"{result[0]}")
break
elif result == search[-1]:
print("No match")
I think you are just counting the STRs repetitions in the sequence, not the maximum consecutive STR repetitions. This is what the problem asks

Binary Search to search a list

I have a code which first sorts the emails into alphabetical order and then attempts to use binary search to search a user inputted email from a list. However, I have been stuck on how to do this for so long and haven't found any solutions on the error I get and how to fix it. Here is my code
def BubbleSort(logindata):
NoSwaps = 1
N = len(logindata)
logindata = list(logindata)
while NoSwaps == 1:
Count = 1
NoSwaps = 0
for Count in range(N-1):
if logindata[Count] > logindata[Count+1]:
temp = logindata[Count]
logindata[Count] = logindata[Count+1]
logindata[Count+1]=temp
NoSwaps=1
return tuple(logindata)
def BinarySearch(logindata,ItemSought):
First=0
Last=len(logindata)-1
ItemFound = False
SearchFailed = False
while ItemFound == False or SearchFailed == False:
Midpoint = (First + Last) // 2
if logindata[Midpoint] == ItemSought:
ItemFound = True
print("Item Found")
break
elif logindata[Midpoint] > ItemSought:
Last = Midpoint - 1
else:
First = Midpoint + 1
if __name__ == "__main__":
logindata=["tom#gmail.com","Password1"],["harry#gmail.com","Password2"],["jake#gmail.com","Password3"]
logindata=BubbleSort(logindata)
print(logindata)
ItemSought=input("Enter username")
BinarySearch(logindata,ItemSought)
The error I currently get is :
elif logindata[Midpoint] > ItemSought:
TypeError: unorderable types: list() > str()
You're comparing a username/password pair (e.g. ["tom#gmail.com","Password1"]) with a username (e.g. "tom#gmail.com").
You need to extract the username from logindata[Midpoint] before comparing it to ItemSought.

Categories

Resources