I am very new to this and would greatly appreciate some insight.
I am trying to learn Python by doing something useful; write a script
that will count and output my aggregated visits to my website. I have
a separate text file that holds the list of uri strings that I want to
count and then this code. The log is sampleLog.txt.
The problem is that it says all the preceding uris are 0 (they are
not) and only the last string actually is counted....why is that?
def stats():
import sys
import string
#read the file of current urls - presumes it exists already
x = open('urlList.t xt')
# note this reads as a file, not a list
urlFile = x.read()
# don't need to close but should
x.close()
#list what is in text file of urls
print "Here is what we check now:\n", urlFile
print "\n"
# len(listName) gives # of list elements
#turn url listings into list
z = open('urlList.t xt')
urlList = z.readlines()
#open log file
log = open('sampleLog .txt')
logFile = log.read()
#initialize counter at 0
i = 0
# loop through to search for urls
while i < len(urlList):
# put element into var
check = urlList[i]
#print out # found and what it was
print check, " found" , string.count(lo gFile, check) ,"times
\n"
# increment for next item - can't do i ++
i = i + 1
z.close() 3 3608
"Jonathan Driller" <jd******@orchi d.org> wrote in message
news:a8******** *************** ***@posting.goo gle.com... I am very new to this and would greatly appreciate some insight. I am trying to learn Python by doing something useful; write a script that will count and output my aggregated visits to my website. I have a separate text file that holds the list of uri strings that I want to count and then this code. The log is sampleLog.txt.
The problem is that it says all the preceding uris are 0 (they are not) and only the last string actually is counted....why is that?
def stats(): import sys import string #read the file of current urls - presumes it exists already x = open('urlList.t xt') # note this reads as a file, not a list urlFile = x.read() # don't need to close but should x.close() #list what is in text file of urls print "Here is what we check now:\n", urlFile print "\n"
# len(listName) gives # of list elements
#turn url listings into list z = open('urlList.t xt') urlList = z.readlines() #open log file log = open('sampleLog .txt') logFile = log.read() #initialize counter at 0 i = 0 # loop through to search for urls while i < len(urlList): # put element into var check = urlList[i] #print out # found and what it was print check, " found" , string.count(lo gFile, check) ,"times \n" # increment for next item - can't do i ++ i = i + 1 z.close()
The lines you're reading from your test file all end
in a newline, so that may be the reason you're not
finding them in the log file. I suspect that you didn't
end your test file with a return, so that line was
found.
change
check = urlList[i]
to
check = urlList[i].strip()
and it might work better.
Also, your imports belong at the module level,
not inside the definition.
John Roth
"Jonathan Driller" <jd******@orchi d.org> wrote in message
news:a8******** *************** ***@posting.goo gle.com... I am very new to this
A common newbie programmer mistake, having read 'comment your code',
is to overcomment to the point of giving a parallel plain-text version
of the code, as you did. Your worse example of this is
#initialize counter at 0 i = 0
The result is to make the code harder and more painful to read,
especially for an experienced programmer, rather than easier, which is
the proper purpose of comments. If you are going to write a parallel
psuedocode version, make it truly parallel by using your space key (or
tab key in editor that converts to spaces) to put the comments over to
the right:
i = 0
#initialize counter at 0
Then someone can much more easily ignore the redundant comments to
read the actual code.
There is no need to read urlList.txt twice.
z = open('urlList.t xt')
urlList = z.readlines()
can be replaced by
urlList = urlFile.split(' \n')
Unless you need to write code for 1.5.2, I recommend you learn now to
write string methods as methods rather than as string module
functions. The latter is a redundant access path for backwards
compatibility that will probably disappear in the future. If you look
in the string module, you will find, for instance, def count(s,
*args): return s.count(*args), so all you are doing is wrapping the
method calls in an extra function call.
I hope Johm's answer is the one you needed.
Terry J. Reedy
Thanks.
That worked beautifully - except that I kept getting errors if I moved
the import statements out of the def... "invalid syntax"
So, now it is (with the changed comments per Terry's suggestion to be
added):
def stats():
import sys
import string
#read the file of current urls that are to be checked - presumes
it exists already
x = open('urlList.t xt')
# note this reads as a file, not a list
urlFile = x.read()
# don't need to close but should
x.close()
#list what is in text file of urls
print "Here is what we check now:\n", urlFile
print "\n"
#prompt to add additional urls - use raw so quotes not nec
addItem = raw_input('Ente r an additional URL in quotes:' )
# can't append() to a file, must list.append() or do this way
urlList = urlFile + "\n" + addItem
#write additional urls to list
y = open('urlList.t xt', 'w')
y.write(urlList )
y.close()
# len(listName) gives # of list elements
#turn url listings into list
z = open('urlList.t xt')
urlList = z.readlines()
#open log file
log = open('sampleLog .txt')
logFile = log.read()
#initialize counter at 0
i = 0
# loop through to search for urls
while i < len(urlList):
# put element into var
check = urlList[i].strip()
#print out # found and what it was
print check, " found" , string.count(lo gFile, check) ,"times
\n"
# increment for next item - can't do i ++
i = i + 1
z.close() This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Anand Pillai |
last post by:
This is for folks who are familiar with asynchronous event handling in
Python using the asyncore module.
If you have ever used the asyncore module, you will realize that it's
event loop does not have a programmable exit condition. It keeps
looping till the channels in its socket map (a dictionary) are closed
and don't have any pending reads/writes.
If you are using Python threads in your application, by using either
the threading or...
|
by: Ravi |
last post by:
Hi All,
I am trying to execute a select statement using the DBI module
of perl in a for loop. I am getting a strange behaviour, the select
statement is excuting correctly only for the last element in the for
loop.
I am including the portion of the code :
#Get the connection to the database
my $dbh = &getConnection();
my @acodes;
|
by: hall |
last post by:
Hi.
I've come across someting strange. I was trying to make a for-loop
execute repetadly until the function called inside it does not return
true during the entire loop (see program below).
The two lines that confuse me are marked as (1) and (2).
count=0;
bool s(true);
|
by: Dave Veeneman |
last post by:
In a for-loop, is a calculated expression re-calculated on each pass through
the loop, or only once, when the loop is initialized? For example, assume
the following loop:
for (int i = 0; i < myArray.Length - 1; i++)
{
// code here
}
Is "myArray.Length - 1" calculated once, or on each pass through the loop?
|
by: Nancy |
last post by:
Greetings:
First, I apologize if my posting format is improper. The code below does
what I intended it to do, but presently only displays 1 table entry. I've
grown it to this point, but really need it to loop through the table and do
everything where data_store_no matches $store_no. I've tried placing where
at a couple different points with no real success - it either doesn't work
at all, exceeds the time allowed for a process...
| |
by: tom fredriksen |
last post by:
Hi
I was doing a simple test of the speed of a "maths" operation and when I
tested it I found that removing the loop that initialises the data array
for the operation caused the whole program to spend twice the time to
complete. If the loop is included it takes about 7.48 seconds to
complete, but when removed it takes about 11.48 seconds.
Does anybody have a suggestion as to why this is so and whether I can
trust the results of the...
|
by: Claudio Grondi |
last post by:
Sometimes it is known in advance, that the time spent in a loop will be
in order of minutes or even hours, so it makes sense to optimize each
element in the loop to make it run faster.
One of instructions which can sure be optimized away is the check for
the break condition, at least within the time where it is known that the
loop will not reach it.
Any idea how to write such a loop?
e.g.
|
by: Rick |
last post by:
The following code will enter an infinate loop when in ReadChars. I can only
make it happen when reading a Stream and with this particular XML. If I use
the ReadInnerXml call rather than my own ReadElementBodyAsXml the code works,
but is less efficent. ReadElementBodyAsXml is required by my application
with .Net Framework 1.1.
The code breaks on the second call to ReadElementBodyAsXml with the inner xml:
</EGDConfigExtension>...
|
by: Brad |
last post by:
Hi folks,
I'm still fairly new to programming in python and programming in
general. A friend of mine is in a CompSci 101 course and was working
on a slider game when he encountered a problem. We eventually figured
out what the problem was and built a test case to help solve it, but I
can't for the life of me figure out the why behind it. I tried
googling it and searching the list but didn't find anything that
really explained it. I'm...
|
by: tshad |
last post by:
Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?
foreach (Racecar racecar in RaceCarCollection)
{
...
if last row do something?
}
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |