Hi I'm new to python. I am trying to add different key value pairs to a dictionary depending on different if statements like the following:
def getContent(file)
for line in file:
content = {}
if line.startswith(titlestart):
line = line.replace(titlestart, "")
line = line.replace("]]></title>", "")
content["title"] = line
elif line.startswith(linkstart):
line = line.replace(linkstart, "")
line = line.replace("]]>", "")
content["link"] = line
elif line.startswith(pubstart):
line = line.replace(pubstart, "")
line = line.replace("</pubdate>", "")
content["pubdate"] = line
return content
print getContent(list)
However, this always returns the empty dictionary {}.
I thought it was variable scope issue at first but that doesn't seem to be it. I feel like this is a very simple question but I'm not sure what to google to find the answer.
Any help would be appreciated.
You reinitialize content for every line, move the initialization outside of the loop:
def getContent(file)
content = {}
for line in file:
etc.
Related
I have a function:
def get_translations(string):
"""stuff"""
list1 = []
empty = []
lines = string.splitlines()
order = 1 if string.split(',')[0] == "english" else -1
if 'english,māori' in string:
for seperate_words in lines:
list1.append(tuple(seperate_words.split(",")[::order]))
return list1[1:]
if 'māori,english' in string:
for seperate_words in lines:
list1.append(tuple(seperate_words.split(",")[::order]))
return list1[1:]
else:
print("Header language not recognized!")
return empty
I am trying to call this function in a new function get_translations_from_file so I can perform what the first function is meant to do. This is because I am trying to open a file and use that file as the string for the first function. This is what I have tried to call the first function but I have had no success:
def get_translations_from_file(filename):
"""stuff"""
file = open(filename)
string = file.read()
get_translations(string)
The test is:
filename = 'places.txt'
for terms in get_translations_from_file(filename):
print(terms)
The contents of the file is:
english,māori
New Zealand,Aotearoa
North Island,Te Ika-a-Māui
South Island,Te Waipounamu
Wellington,Te Whanganui a Tara
Christchurch,Ōtautahi
Hamilton,Kirikiriroa
Auckland,Tāmaki Makaurau
You are calling get_translations, but ignoring the return value. Since get_translations_from_file has no explicit return statement, it implicitly returns None. To make a long story short, you need to return the value from get_translations:
def get_translations_from_file(filename):
"""stuff"""
file = open(filename)
string = file.read()
return get_translations(string) # Here!
I'm trying to replace a specific part of a line in a txt file, but it says "AttributeError: 'list' object has no attribute 'replace'".
This is part of my code:
with open("credentials.txt",'r+') as f:
credentials_array = f.readlines() # credentials_array contains the txt file's contents, arranged line by line. so credentials_array[0] would be the first login info in the file
lines_in_credentials = len(credentials_array) # if there are 7 credentials in the text file, lines_in_credentials = 7.
while x < lines_in_credentials:
if user in credentials_array[x]: # go through each line in turn to see if the login_username is in one. line 1, credentials_array[1].
credentials_desired_line = credentials_array[x]
username_password_score = credentials_array[x].split(",") # username_password_score is the contents of each line, the contents are split by commas
stored_username = username_password_score[0] # username is part 1
stored_password = username_password_score[1] # password is part 2
stored_score = username_password_score[2] # score is part 3
stored_score_int = int(stored_score)
if user == stored_username:
if new_score > stored_score_int:
print("Congratulations! New high score!")
print(stored_score_int,"-->",new_score)
credentials_array_updated = stored_username+","+stored_password+","+str(new_score) # reassign the array[x] to having new_score at the end instead of stored_score
credentials_array.replace(credentials_array[x],credentials_array_updated)
break
Is there any other way to do it?
Your missing a line setting x = 0 in your presented problem, but that's not important - I think that's just a typo you've missed when writing it out.
Your line:
credentials_array.replace(credentials_array[x], credentials_array_updated)
is your problem. Try:
credentials_array[x].replace(credentials_array[x], credentials_array_updated)
replace operates on the string, and you want to replace the string within credentials_array[x], not the whole list.
Now, I have assumed there are more entries to credentials_desired_line than what you've outlined in username_password_score. Otherwise you could do just a straight replacement such as:
credentials_array[x] = credentials_array_updated
As a bigger change, you could try this:
iLines = 0
with open("credentials.txt",'r+') as f:
credentials_array = f.readlines()
for line in credentials_array:
if user in line: #user we want is in this line
currScore = int(credentials_array[x].split(",")[2])
if new_score > currScore:
print("Congratulations! New high score!")
print(Str(currScore),"-->",str(new_score))
credentials_array[iLines].replace(str(currScore),str(newScore))
break
iLines =+1
With you wanting to update the text file, the minimal mod to your code would be to put this at the end (beyond/outside) the previous "with open()" loop:
with open('credentials.txt', 'w') as f:
for line in credentials_array:
f.write("%s\n" % line)
I have this code in Python which adds a line to a given file. The problem is that i want to add this blazegraph_address only if there isn't the same line already in the file. If there is, I don't need the address to be added to the file. The function code for this is below:
def write_to_address_file(blazegraph_address):
address_path = open("./saved_info/saved_address.txt", "a")
with open("./saved_info/saved_address.txt") as f:
seen = set()
seen.add(f.read())
print("SEEN",seen)
if blazegraph_address in seen:
print("ADDRESS IN SET ALREADY")
else:
seen.add(blazegraph_address)
address_path.write("\n"+str(blazegraph_address))
The problem is that the set populates with the file contents even though there are duplicates. How to only add to the file if the address is not in the file already?
Your code read the entire file, not line by line.
For this, you need to use create your set with the lines:
Modify:
seen = set()
seen.add(f.read())
With:
seen = set(f.read().split('\n'))
def write_to_address_file(blazegraph_address):
address_path = open("./saved_info/saved_address.txt", "a")
with open("./saved_info/saved_address.txt", "r") as msg:
data = msg.read().splitlines()
if blazegraph_address in data:
print("ADDRESS IN SET ALREADY")
else:
address_path.write("\n"+str(blazegraph_address))
I'm making a program that stores data in a text file, I can search for data line by line, and I made a (delete function) that is quoted below, making a variable 'a' adding to it the (non deleted lines), and ask before deletion for results and if not confirmed it would be added also to 'a', then rewrite the (file) with'a' omitting the deleted lines.
THE PROBLEM IS:
all results are deleted not only the confirmed one desbite that:
#deleting line
confirm = input('confirm to delete [y]/[n]>>')
if confirm != 'y':
a += line
so, why did this problem happen and how to fix it?
Next is the whole code of delete function:
searching = input('enter any information about query: ')
searching = searching.lower() # converting words in lower case
f = open(file, 'r')
lines = f.readlines()
f.close()
print('Word | Definition | Remarks')
a = '' # we will store our new edited text here
for line in lines:
line_lower_case = line.lower() # changing line in lower case temporary
# because contact != COntact and will not appear in searcch
if searching in line_lower_case:
print('Query found')
print()
print('>>',line, end = '') # printing words in the same case as been added
# end = '', to prevent printing new line avoiding extra empty line
#deleting line
confirm = input('confirm to delete [y]/[n]>>')
if confirm != 'y':
a += line
#elif confirm =='y':
# pass # it will just do nothing, and will not add line to 'a'
continue # to search for more queries with the same searching entry
print()
a += line #we add each line to the 'a' variable
f = open(file,'w')
f.write(a) #we save our new edited text to the file
f.close()
I changed the indentations of the program and that was the issue as I agreed with #TheLazyScripter and that should work now if I understood your problem correctly, I did a bunch of tests and they did work. I noticed that you didn't define what input file will be and I add that line of code at line 3 which will through an error if the file not defined.
searching = input('enter any information about query: ')
searching = searching.lower() # converting words in lower case
file = "test.txt" #your file
f = open(file, 'r')
lines = f.readlines()
f.close()
print('Word | Definition | Remarks')
a = '' # we will store our new edited text here
for line in lines:
line_lower_case = line.lower() # changing line in lower case temporary
# because contact != COntact and will not appear in searcch
if searching in line_lower_case:
print('Query found')
print()
print('>>',line, end = '') # printing words in the same case as been added
# end = '', to prevent printing new line avoiding extra empty line
#deleting line
confirm = input('confirm to delete [y]/[n]>>')
if confirm != 'y':
a += line
#elif confirm =='y':
# pass # it will just do nothing, and will not add line to 'a'
continue # to search for more queries with the same searching entry
print()
a += line #we add each line to the 'a' variable
f = open(file,'w')
f.write(a) #we save our new edited text to the file
f.close()
I was trying to implement this block of code from Generator not working to split string by particular identifier . Python 2 but I found two bugs in it that I can’t seem to fix.
Input:
#m120204
CTCT
+
~##!
#this_one_has_an_at_sign
CTCTCT
+
#jfik9
#thisoneisempty
+
#empty line after + and then empty line to end file (2 empty lines)
The two bugs are:
(i) when there is a # that starts the line of code after the ‘+’ line such as the 2nd entry (#this_one_has_an_at_sign)
(ii) when there line following the #identification_line or the line following the ‘+’ lines are empty like in 3rd entry (#thisoneisempty)
I would like the output to be the same as the post that i referenced:
yield (name, body, extra)
in the case of #this_one_has_an_at_sign
name= this_one_has_an_at_sign
body= CTCTCT
quality= #jfik9
in the case of #thisoneisempty
name= thisoneisempty
body= ''
quality= ''
I tried using flags but i can’t seem to fix this issue. I know how to do it without using a generator but i’m going to be using big files so i don’t want to go down that path. My current code is:
def organize(input_file):
name = None
body = ''
extra = ''
for line in input_file:
line = line.strip()
if line.startswith('#'):
if name:
body, extra = body.split('+',1)
yield name, body, extra
body = ''
name = line
else:
body = body + line
body, extra = body.split('+',1)
yield name, body, extra
for line in organize(file_path):
print line