for this function, i need to traverse through a file and count each line based on certain signifiers. If that certain signifier is present in the line, i need to add the string as a key to the dictionary and increment its value by one each time its present. I am not outright looking for the answer, I am just lost as to what I have done wrong and where I can proceed from here.
Both of the counter variables and the dictionary are returning empty. I need them to return the values based on what is present on a given file.
file line example:
RT #taylorswift13: Feeling like the luckiest person alive to get to take these brilliant artists out on tour w/ me: #paramore, #beabad00bee & #OwennMusic. I can’t WAIT to see you. It’s been a long time coming 🥰
code:
def top_retweeted(tweets_file_name, num_top_retweeted):
total_tweets = 0
total_retweets = 0
retweets_users = {}
f_read = open(tweets_file_name, "r")
f_write = open(tweets_file_name, "w")
lines = f_read.readlines()
for line in lines:
total_tweets =+1
elements = line.split(":")
for element in elements:
if "RT" in element:
total_retweets =+1
user_name = element.split()
retweet_users[user_name]=+1
print("There were " + str(total_tweets) + " tweets in the file, " + str(total_retweets) + " of which were retweets")
return retweets_user
f_read = open(tweets_file_name, "r")
f_write = open(tweets_file_name, "w")
You're opening the file for reading and then also opening it for writing, which destroys the existing contents.
Related
I have a file with a bunch of albums and the list of songs of each album after it. Names of albums start with # and names of songs start with *. I'm trying to make a script that will give me all the songs in a specific album but it keeps printing all the songs in the entire file. Here is the code I wrote
def song_list(album):
albumDB = open('Pink_Floyd_DB.txt','r')
song_list = []
i = 0
lines = albumDB.readlines()
for line in lines:
if album in line:
for song_name in lines:
if '*' in song_name:
song = song_name.split('::', 1)[0]
song_list.insert(i,song)
i += 1
for song in song_list:
print(song)
You can create a <key, values> dictionary in which the keys are the album names and the values the list of corresponding songs dict_song: <albums, songs>.
dict_album = {}
with open(r'album.txt') as text:
album = ''
song = ''
for line in text:
#line = line.rstrip("\n")
line = line.strip()
if line.startswith('#'):
album = line.replace("#", "", 1).strip() # remove only first occurency
dict_album[album] = []
elif line.startswith('*'):
song = line.replace("*", "", 1).strip() # remove only first occurency
dict_album[album].append(song)
else:
# should never occur
continue
To access the dictionary you only need to access it directly by key, or by using the .get() function, which takes as its first parameter the key (album name) and optionally you can put as a second parameter a value that will be returned when the key is not found in the dictionary (eg. "Album not found")
query_album = "The Wall"
print(dict_album.get("The Wall", "Album not found"))
and you get the list of songs:
['Another Brick in the Wall Pt 1',
'Comfortably Numb',
'Vera']
Your code explicitly loops over all the lines, and prints all of the songs from all albums each time it sees a matching album (with double newlines, because print adds one of its own). You are also reinventing list.append() for no good reason.
If I'm guessing correctly that your file looks something like
# The Wall
* Another Brick in the Wall Pt 1
* Comfortably Numb
* Vera
# Wish You Were Here
* Shine On You Crazy Diamond
* Wish You Were Here
then you will simply want to read up to the next # line.
with open(file) as songs:
found = False
for line in songs:
line = line.rstrip("\n")
if line == "# " + album:
found = True
continue
if line.startswith("#"):
if found:
break
if line.startswith("*") and found:
print(line.lstrip("* "))
A better approach for a more complex program would be to open and parse the file just once, then manipulate the resulting structure in memory. But then, a better solution still is to ditch this ad-hoc format, and save your database in a standard machine-readable format like JSON or YAML. Here's a simple YAML stucture of the data above:
---
The Wall:
- Another Brick in the Wall Pt 1
- Comfortably Numb
- Vera
Wish You Were Here:
- Shine On You Crazy Diamond
- Wish You Were Here
and you'd read it with
import yaml
with open(yamlfile) as data:
albums = yaml.safe_load(data)
Now, albums["The Wall"] returns the list of songs from that album.
I have tried multiple ways to do this but I struggle. I am new to Python trying to learn currently.
CustomerList = []
Customers = {}
Dates = {}
while True:
Customer_Name = input("Customer's Name:")
CustomerList.append(Customer_Name)
Customers_Address = input("Customer's Address:")
if Customer_Name in Customers:
Customers[Customer_Name]['Orders'] += 1
Customers[Customer_Name]['TotalAmount'] = Total_Amount
else:
Customers[Customer_Name] = {}
Customers[Customer_Name]['Address'] = Customers_Address
Customers[Customer_Name]['Orders'] = 1
Customers[Customer_Name]['TotalAmount'] = 0
file1 = open('Orders_Per_Users.txt', 'w')
file1.write(Customer_Name + " has ordered " + str(Customers[Customer_Name]['Orders']) + " times in total\n")
file1.close()
This is the output
And this is what I get exported from this output
What I want to .txt export for example is.
John has ordered 1 times in total
Mike has ordered 1 times in total
etc
etc
Opening with a 'w' tag means you are opening the file in write mode. write mode overwrites the previously existing text if any or creates a new file if the file doesnt exist.So what you might wanna do is opening it in 'a' mode (append mode) so that it doesnt overwrite the file but just appends text to it
file1 = open('Orders_Per_Users.txt', 'a')
file1.write(Customer_Name + " has ordered " + str(Customers[Customer_Name]['Orders']) + "
times in total\n")
your file permission should be append
w -
Opens in write-only mode. The pointer is placed at the beginning of
the file and this will overwrite any existing file with the same name.
It will create a new file if one with the same name doesn't exist
a -
Opens a file for appending new information to it. The pointer is
placed at the end of the file. A new file is created if one with the
same name doesn't exist. .
file1 = open('Orders_Per_Users.txt', 'a')
I hope you're enjoying your learning :)
problems are:
your code just update the text each time you add an item because of the mode of write/read operation of the file, you coded it like this:
file1 = open('Orders_Per_Users.txt', 'w')
While the correct mode is 'a' instead of 'w' to append to the file without erasing old written text!
NOTE: even if you correct it to be 'a' another issue will appear! the line will be written again in entering new order!
So what you should do is closing the file file1.close() each time you write to it in the while so your code will be looks like this:
CustomerList = []
Customers = {}
Dates = {}
while True:
Customer_Name = input("Customer's Name:")
CustomerList.append(Customer_Name)
Customers_Address = input("Customer's Address:")
if Customer_Name in Customers:
Customers[Customer_Name]['Orders'] += 1
Customers[Customer_Name]['TotalAmount'] = Total_Amount
else:
Customers[Customer_Name] = {}
Customers[Customer_Name]['Address'] = Customers_Address
Customers[Customer_Name]['Orders'] = 1
Customers[Customer_Name]['TotalAmount'] = 0
file1 = open('Orders_Per_Users.txt', 'a')
file1.write(Customer_Name + " has ordered " + str(Customers[Customer_Name]['Orders']) + " times in total\n")
file1.close()
Here's the code I use to read from the file
def load_leaderboard(file_name, leader_names, leader_scores):
leaderboard_file = open(file_name, "r") # need to create the file ahead of time in same folder
# use a for loop to iterate through the content of the file, one line at a time
# note that each line in the file has the format "leader_name,leader_score" for example "Pat,50"
for line in leaderboard_file:
leader_name = ""
leader_score = ""
index = 0
# TODO 1: use a while loop to read the leader name from the line (format is "leader_name,leader_score")
while (line[index] != ","):
leader_name = leader_name + line[index]
index = index + 1
print("leader name is " + leader_name)
# TODO 2: add the leader name to the list
leader_names.append(leader_name)
# TODO 3: read the player score using a similar loop'
index += 1
while(line[index] != '\n'):
leader_score += line[index]
index += 1
print('The score for this person is:' + leader_score)
# TODO 4: add the player score to the list
leaderboard_file.close()
When this code runs it works correctly, only once it reads everything from the text file it deletes all the information from the text file itself. I thought it would be fine since i put the open() function on readonly. But its not, how do i keep it from deleting the information from the original file?
Here is what I am trying to do:
I am trying to solve an issue that has to do with wrapping in a text file.
I want to open a txt file, read a line and if the line contains what I want it to contain, check the next line to see if it does not contain what is in the first line. If it does not, add the line to the first line.
import re
stuff = open("my file")
for line in stuff:
if re.search("From ", line):
first = line
print first
if re.search('From ', handle.next()):
continue
else: first = first + handle.next()
else: continue
I have looked a quite a few things and cannot seem to find an answer. Please help!
I would try to do something like this, but this is invalid for triples of "From " and not elegant at all.
lines = open("file", 'r').readlines()
lines2 = open("file2", 'w')
counter_list=[]
last_from = 0
for counter, line in enumerate(lines):
if "From " in line and counter != last_from +1:
last_from = counter
current_count = counter
if current_count+1 == counter:
if "From " in line:
counter_list.append(current_count+1)
for counter, line in enumerate(lines):
if counter in counter_list:
lines2.write(line)
else:
lines2.write(line, '\n')
Than you can check the lines2 if its helped.
You could also revert order of lines, then check in next line not in previous. That would solve your problem in one loop.
Thank you Martjin for helping me reset my mind frame! This is what I came up with:
handle = open("my file")
first = ""
second = ""
sent = ""
for line in handle:
line = line.rstrip()
if len(first) > 0:
if line.startswith("From "):
if len(sent) > 0:
print sent
else: continue
first = line
second = ""
else:
second = second + line
else:
if line.startswith("From "):
first = line
sent = first + second
It is probably crude, but it definitely got the job done!
I'm writing a program in Python that will store Student IDs, names, and D.O.B.s.
The program gives the user the ability to remove, add, or find a student. Here is the code:
students={}
def add_student():
#Lastname, Firstname
name=raw_input("Enter Student's Name")
#ID Number
idnum=raw_input("Enter Student's ID Number")
#D.O.B.
bday=raw_input("Enter Student's Date of Birth")
students[idnum]={'name':name, 'bday':bday}
def delete_student():
idnum=raw_input("delete which student:")
del students[idnum]
def find_student():
print "Find"
menu = {}
menu['1']="Add Student."
menu['2']="Delete Student."
menu['3']="Find Student"
menu['4']="Exit"
while True:
options=menu.keys()
options.sort()
for entry in options:
print entry, menu[entry]
selection=raw_input("Please Select:")
if selection =='1':
add_student()
elif selection == '2':
delete_student()
elif selection == '3':
find_students
elif selection == '4':
break
else:
print "Unknown Option Selected!"
The problem I am having is I cannot figure out how to have the program save any added records to a file when the program ends. It also would need to read back the records when the program restarts.
I keep trying to find tutorials for this sort of thing online, but to no avail. Is this the sort of code I'd want to add?:
f = open("myfile.txt", "a")
I'm new to Python so any help would be appreciated. Thanks so much.
It depends, if you want to actually save python objects, check out Pickle or Shelve, but if you just want to output to a text file, then do the following:
with open('nameOfYourSaveFile', 'w') as saveFile:
#.write() does not automatically add a newline, like print does
saveFile.write(myString + "\n")
Here's an answer that explains the different arguments to open, as in w, w+, a, etc.
As an example, say we have:
with open('nameOfYourSaveFile', 'w') as saveFile:
for i in xrange(10):
saveFile.write(name[i] + str(phoneNumber[i]) + email[i] + "\n")
To read the file back, we do:
names = []
numbers = []
emails = []
with open('nameOfYourSaveFile', 'r') as inFile:
for line in inFile:
#get rid of EOL
line = line.rstrip()
#random example
names.append(line[0])
numbers.append(line[1])
emails.append(line[2])
#Or another approach if we want to simply print each token on a newline
for word in line:
print word
import pickle,os
if os.path.exists("database.dat"):
students = pickle.load(open("database.dat"))
else:
students = {}
... #your program
def save():
pickle.dump(students,open("database.dat","w"))