473,406 Members | 2,816 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

help with lists and writing to file in correct order

hey folks,

have a logic question for you. appreciate the help in advance.

i am scraping 3 pieces of information from the html namely the food
name , store name and price. and i am doing this for many different
food items found ni the html including pizza, burgers, fries etc. what
i want is to write out to a text file in the following order:

pizza, pizza hut, 3.00
burgers, burger king, 4.00
noodles, panda inn, 2.00

html is below. does anyone have good recommendation for how to setup
the code in such a manner where it writes to the text file in th order
listed previously? any attempt i have made seems to write to the file
like this

noodles, panda inn, 3
noodles, panda inn, 4
noodles, panda inn, 2
HTML
<tr class="base"><td class="tall"><a name="D0L1" "href="his/food"
target="_blank">

<td class="desc"><h2 id="foodName">pizza</h2>

<div class="store"><a name="D0L3" "href="/xPopups/nojs"
target="_blank"><b>pizza hutt</b></a></div>

<td class="price">3.00</td>
<tr>

Dec 26 '05 #1
17 1355
On Mon, 26 Dec 2005 13:54:37 -0800, homepricemaps wrote:
hey folks,

have a logic question for you. appreciate the help in advance.

i am scraping 3 pieces of information from the html namely the food
name , store name and price. and i am doing this for many different
food items found ni the html including pizza, burgers, fries etc. what
i want is to write out to a text file in the following order:

pizza, pizza hut, 3.00
burgers, burger king, 4.00
noodles, panda inn, 2.00

html is below. does anyone have good recommendation for how to setup
the code in such a manner where it writes to the text file in th order
listed previously? any attempt i have made seems to write to the file
like this

noodles, panda inn, 3
noodles, panda inn, 4
noodles, panda inn, 2


Instead of posting the HTML, how about if you post your code? Unless we
see your code, how do you expect us to find the bug in it?

--
Steven.

Dec 27 '05 #2
sorry guys, here is the code

for incident in bs('a', {'class' : 'price'}):
price = ""
for oText in incident.fetchText( oRE):
price += oText.strip() + "','"

for incident in bs('div', {'class' : 'store'}):
store = ""
for oText in incident.fetchText( oRE):
store += oText.strip() + "','"

for incident in bs('h2', {'id' : 'food'}):
food = ""
for oText in incident.fetchText( oRE):
food += oText.strip() + "','"

Dec 27 '05 #3
On Mon, 26 Dec 2005 17:44:43 -0800, homepricemaps wrote:
sorry guys, here is the code

for incident in bs('a', {'class' : 'price'}):
price = ""
for oText in incident.fetchText( oRE):
price += oText.strip() + "','"

for incident in bs('div', {'class' : 'store'}):
store = ""
for oText in incident.fetchText( oRE):
store += oText.strip() + "','"

for incident in bs('h2', {'id' : 'food'}):
food = ""
for oText in incident.fetchText( oRE):
food += oText.strip() + "','"

This is hardly all your code -- where is the part where you actually
*write* something to the file? The problem is you are writing the same
store and food to the file over and over again. After you have collected
one line of store/food, you must write it to the file immediately, or at
least save it in a list so you can write the lot at the end.
--
Steven.

Dec 27 '05 #4
here is the write part:

out = open("test.txt", 'a')
out.write (store+ food+ price + "\n")
out.close()
Steven D'Aprano wrote:
On Mon, 26 Dec 2005 17:44:43 -0800, homepricemaps wrote:
sorry guys, here is the code

for incident in bs('a', {'class' : 'price'}):
price = ""
for oText in incident.fetchText( oRE):
price += oText.strip() + "','"

for incident in bs('div', {'class' : 'store'}):
store = ""
for oText in incident.fetchText( oRE):
store += oText.strip() + "','"

for incident in bs('h2', {'id' : 'food'}):
food = ""
for oText in incident.fetchText( oRE):
food += oText.strip() + "','"

This is hardly all your code -- where is the part where you actually
*write* something to the file? The problem is you are writing the same
store and food to the file over and over again. After you have collected
one line of store/food, you must write it to the file immediately, or at
least save it in a list so you can write the lot at the end.
--
Steven.


Dec 27 '05 #5
the problem with writing to teh file immidiately is that it ends up
writing all food items together, and then all store items and then all
prices

i want

food, store, price
food, store, price

Dec 27 '05 #6
ho***********@gmail.com wrote:
the problem with writing to teh file immidiately is that it ends up
writing all food items together, and then all store items and then all
prices

i want

food, store, price
food, store, price

Well, if it all fits in memory, append each to its own list, and then
either finally if you can or periodically if you must:

for food, store, price in zip(foods, stores, prices):
<do some writing.>

--
-Scott David Daniels
sc***********@acm.org
Dec 27 '05 #7
sorry for asking such beginner questions but i tried this and nothing
wrote to my text file

for food, price, store in bs(food, price, store):
out = open("test.txt", 'a')
out.write (food + price + store)
out.close()
while if i write the following without the for i at least get
something?
out = open("test.txt", 'a')
out.write (food + price + store)
out.close()
Scott David Daniels wrote:
ho***********@gmail.com wrote:
the problem with writing to teh file immidiately is that it ends up
writing all food items together, and then all store items and then all
prices

i want

food, store, price
food, store, price

Well, if it all fits in memory, append each to its own list, and then
either finally if you can or periodically if you must:

for food, store, price in zip(foods, stores, prices):
<do some writing.>

--
-Scott David Daniels
sc***********@acm.org


Dec 27 '05 #8

homepricem...@gmail.com wrote:
sorry for asking such beginner questions but i tried this and nothing
wrote to my text file

for food, price, store in bs(food, price, store):
out = open("test.txt", 'a')
out.write (food + price + store)
out.close()
while if i write the following without the for i at least get
something?
out = open("test.txt", 'a')
out.write (food + price + store)
out.close()

pull the open() and close() call out of the loop. And use some other
name for the variables as they are very confusing and could be error
prone to.

Dec 27 '05 #9
On Mon, 26 Dec 2005 20:56:17 -0800, homepricemaps wrote:
sorry for asking such beginner questions but i tried this and nothing
wrote to my text file

for food, price, store in bs(food, price, store):
out = open("test.txt", 'a')
out.write (food + price + store)
out.close()
What are the contents of food, price and store? If "nothing wrote to my
text file", chances are all three of them are the empty string.

while if i write the following without the for i at least get
something?
out = open("test.txt", 'a')
out.write (food + price + store)
out.close()


You get "something". That's not much help. But I predict that what you are
getting is the contents of food price and store, at least one of which are
not empty.

You need to encapsulate your code by separating the part of the code that
reads the html file from the part that writes the text file. I suggest
something like this:
def read_html_data(name_of_file):
# I don't know BeautifulSoup, so you will have to fix this...
datafile = BeautifulSoup(name_of_file)
# somehow read in the foods, prices and stores
# for each set of three, store them in a tuple (food, store, price)
# then store the tuples in a list
# something vaguely like this:
data = []
while 1:
food = datafile.get("food") # or whatever
store = datafile.get("store")
price = datafile.get("price")
data.append( (food,store,price) )
datafile.close()
return data

def write_data_to_text(datalist, name_of_file):
# Expects a list of tuples (food,store,price). Writes that list
# to name_of_file separated by newlines.
fp = file(name_of_file, "w")
for triplet in datalist:
fp.write("Food = %s, store = %s, price = %s\n" % triplet
fp.close()
Hope this helps.

--
Steven.

Dec 27 '05 #10
Why don't you use pickle instead of directly writing to the file yourself?
Dec 27 '05 #11
hey steven-your examlpe was very helpful. is there a paragraph symbolg
missing in

fp.write("Food = %s, store = %s, price = %s\n" % triplet
Steven D'Aprano wrote:
On Mon, 26 Dec 2005 20:56:17 -0800, homepricemaps wrote:
sorry for asking such beginner questions but i tried this and nothing
wrote to my text file

for food, price, store in bs(food, price, store):
out = open("test.txt", 'a')
out.write (food + price + store)
out.close()


What are the contents of food, price and store? If "nothing wrote to my
text file", chances are all three of them are the empty string.

while if i write the following without the for i at least get
something?
out = open("test.txt", 'a')
out.write (food + price + store)
out.close()


You get "something". That's not much help. But I predict that what you are
getting is the contents of food price and store, at least one of which are
not empty.

You need to encapsulate your code by separating the part of the code that
reads the html file from the part that writes the text file. I suggest
something like this:
def read_html_data(name_of_file):
# I don't know BeautifulSoup, so you will have to fix this...
datafile = BeautifulSoup(name_of_file)
# somehow read in the foods, prices and stores
# for each set of three, store them in a tuple (food, store, price)
# then store the tuples in a list
# something vaguely like this:
data = []
while 1:
food = datafile.get("food") # or whatever
store = datafile.get("store")
price = datafile.get("price")
data.append( (food,store,price) )
datafile.close()
return data

def write_data_to_text(datalist, name_of_file):
# Expects a list of tuples (food,store,price). Writes that list
# to name_of_file separated by newlines.
fp = file(name_of_file, "w")
for triplet in datalist:
fp.write("Food = %s, store = %s, price = %s\n" % triplet
fp.close()
Hope this helps.

--
Steven.


Dec 28 '05 #12
On Tue, 27 Dec 2005 20:11:59 -0800, homepricemaps wrote:
hey steven-your examlpe was very helpful. is there a paragraph symbolg
missing in

fp.write("Food = %s, store = %s, price = %s\n" % triplet


No, but there is a closing bracket missing:

fp.write("Food = %s, store = %s, price = %s\n" % triplet)
--
Steven.

Dec 28 '05 #13
ho***********@gmail.com wrote:
sorry guys, here is the code

for incident in bs('a', {'class' : 'price'}):
price = ""
for oText in incident.fetchText( oRE):
price += oText.strip() + "','"

for incident in bs('div', {'class' : 'store'}):
store = ""
for oText in incident.fetchText( oRE):
store += oText.strip() + "','"

for incident in bs('h2', {'id' : 'food'}):
food = ""
for oText in incident.fetchText( oRE):
food += oText.strip() + "','"


I would use a loop that finds the row for a single item with something like
for item in bs('tr', {'class' : 'base'}):

then inside the loop fetch the values for store, food and price for that
item and write them to your output file.

Kent
Dec 28 '05 #14
hey kent thanks for your help.

so i ended up using a loop but find that i end up getting the same set
of results every time. the code is here:

for incident in bs('tr'):
data2 = []
for incident in bs('h2', {'id' : 'dealName'}):
product2 = ""
for oText in incident.fetchText( oRE):
product2 += oText.strip() + ';'

for incident in bs('a', {'name' : 'D0L3'}):
store2 = ""
for oText in incident.fetchText( oRE):
store2 += oText.strip() + ';'
for incident in bs('a', {'class' : 'nojs'}):
price2 = ""
for oText in incident.fetchText( oRE):
price2 += oText.strip() + ';'
tuple2 = (product2, store2, price2)
data2.append(tuple2)
print data2

and i end up getting the following instead of unique results

pizza, pizzahut, 3.94
pizza, pizzahut, 3.94
pizza, pizzahut, 3.94
pizza, pizzahut, 3.94

I would use a loop that finds the row for a single item with something like
for item in bs('tr', {'class' : 'base'}):

then inside the loop fetch the values for store, food and price for that
item and write them to your output file.

Kent


Dec 29 '05 #15
ho***********@gmail.com writes:
hey kent thanks for your help.

so i ended up using a loop but find that i end up getting the same set
of results every time. the code is here:

for incident in bs('tr'):
data2 = []
for incident in bs('h2', {'id' : 'dealName'}):
product2 = ""
for oText in incident.fetchText( oRE):
product2 += oText.strip() + ';'

for incident in bs('a', {'name' : 'D0L3'}):
store2 = ""
for oText in incident.fetchText( oRE):
store2 += oText.strip() + ';'
for incident in bs('a', {'class' : 'nojs'}):
price2 = ""
for oText in incident.fetchText( oRE):
price2 += oText.strip() + ';'
tuple2 = (product2, store2, price2)
data2.append(tuple2)
print data2
Two things here that are bad in general:
1) Doing string catenations to build strings. This is slow in
Python. Build lists of strings and join them, as below.

2) Using incident as the index variable for all four loops. This is
very confusing, and certainly part of your problem.
and i end up getting the following instead of unique results

pizza, pizzahut, 3.94
pizza, pizzahut, 3.94
pizza, pizzahut, 3.94
pizza, pizzahut, 3.94


Right. The outer loop doesn't do anything to change what the inner
loops search, so they do the same thing every time through the outer
loop. You want them to search the row returned by the outer loop each
time.

for row in bs('tr'):
data2 = []
for incident in row('h2', {'id' :'dealName'}):
product2list = []
for oText in incident.fetchText(oRE):
product2list.append(OText.strip() + ';')
product2 = ''.join(product2list)
# etc.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Dec 29 '05 #16
hey mike-the sample code was very useful. have 2 questions

when i use what you wrote which is listed below i get told
unboundlocalerror: local variable 'product' referenced before
assignment. if i however chnage row to incident in "for incident in
bs('tr'):" i then get mytuples printed out nicely but once again get a
long list of

[('pizza;','pizza hut;', '3.94;')]
[('pizza;','pizza hut;', '3.94;')]
for row in bs('tr'):
data=[]
for incident in row('h2', {'id' : 'dealName'}):
productlist = []
for oText in incident.fetchText( oRE):
productlist.append(oText.strip() + ';')
product = ''.join(productlist)

for incident in row('a', {'name' : 'D0L3'}):
storelist = []
for oText in incident.fetchText( oRE):
storelist.append(oText.strip() + ';')
store = ''.join(storelist)

tuple = (product, store, price)
data.append(tuple)
print data

ho***********@gmail.com writes:
hey kent thanks for your help.

so i ended up using a loop but find that i end up getting the same set
of results every time. the code is here:

for incident in bs('tr'):
data2 = []
for incident in bs('h2', {'id' : 'dealName'}):
product2 = ""
for oText in incident.fetchText( oRE):
product2 += oText.strip() + ';'

for incident in bs('a', {'name' : 'D0L3'}):
store2 = ""
for oText in incident.fetchText( oRE):
store2 += oText.strip() + ';'
for incident in bs('a', {'class' : 'nojs'}):
price2 = ""
for oText in incident.fetchText( oRE):
price2 += oText.strip() + ';'
tuple2 = (product2, store2, price2)
data2.append(tuple2)
print data2


Two things here that are bad in general:
1) Doing string catenations to build strings. This is slow in
Python. Build lists of strings and join them, as below.

2) Using incident as the index variable for all four loops. This is
very confusing, and certainly part of your problem.
and i end up getting the following instead of unique results

pizza, pizzahut, 3.94
pizza, pizzahut, 3.94
pizza, pizzahut, 3.94
pizza, pizzahut, 3.94


Right. The outer loop doesn't do anything to change what the inner
loops search, so they do the same thing every time through the outer
loop. You want them to search the row returned by the outer loop each
time.

for row in bs('tr'):
data2 = []
for incident in row('h2', {'id' :'dealName'}):
product2list = []
for oText in incident.fetchText(oRE):
product2list.append(OText.strip() + ';')
product2 = ''.join(product2list)
# etc.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.


Dec 30 '05 #17
ho***********@gmail.com wrote:
hey mike-the sample code was very useful. have 2 questions

when i use what you wrote which is listed below i get told
unboundlocalerror: local variable 'product' referenced before
assignment.
You would get this error if you have a <tr> that doesn't have an <hr
id="dealName">. Do you have some <tr> that are not products? If so you
need to filter them out somehow. Or have you misspelled something? Your
sample data has id="foodName" not "dealName".

You might do better with an incremental development. Start with
for row in bs('tr'):
print row

and expand from there. At each step use print statements to make sure
you are finding the data you expect.

Kent

if i however chnage row to incident in "for incident in bs('tr'):" i then get mytuples printed out nicely but once again get a
long list of

[('pizza;','pizza hut;', '3.94;')]
[('pizza;','pizza hut;', '3.94;')]
for row in bs('tr'):
data=[]
for incident in row('h2', {'id' : 'dealName'}):
productlist = []
for oText in incident.fetchText( oRE):
productlist.append(oText.strip() + ';')
product = ''.join(productlist)

for incident in row('a', {'name' : 'D0L3'}):
storelist = []
for oText in incident.fetchText( oRE):
storelist.append(oText.strip() + ';')
store = ''.join(storelist)

tuple = (product, store, price)
data.append(tuple)
print data

Dec 30 '05 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Mike | last post by:
How do I extract a list of lists from a user defined function and print the results as strings for each list?
10
by: Kristian Nybo | last post by:
Hi, I'm writing a simple image file exporter as part of a school project. To implement my image format of choice I need to work with big-endian bytes, where 'byte' of course means '8 bits', not...
11
by: The_Kingpin | last post by:
Hi all, I'm new to C programming and looking for some help. I have a homework project to do and could use every tips, advises, code sample and references I can get. Here's what I need to do....
6
by: James Radke | last post by:
Hello, I have a multithreaded windows NT service application (vb.net 2003) that I am working on (my first one), which reads a message queue and creates multiple threads to perform the processing...
1
by: Rahul | last post by:
Hi Everybody I have some problem in my script. please help me. This is script file. I have one *.inq file. I want run this script in XML files. But this script errors shows . If u want i am...
0
by: gunimpi | last post by:
http://www.vbforums.com/showthread.php?p=2745431#post2745431 ******************************************************** VB6 OR VBA & Webbrowser DOM Tiny $50 Mini Project Programmer help wanted...
51
by: Joerg Schoen | last post by:
Hi folks! Everyone knows how to sort arrays (e. g. quicksort, heapsort etc.) For linked lists, mergesort is the typical choice. While I was looking for a optimized implementation of mergesort...
11
by: rshepard | last post by:
I start with a list of tuples retrieved from a database table. These tuples are extracted and put into individual lists. So I have lists that look like this: . When I concatenate lists, I end up...
1
by: vikjohn | last post by:
I have a new perl script sent to me which is a revision of the one I am currently running. The permissions are the same on each, the paths are correct but I am getting the infamous : The specified...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.