Hello all,
I've been trying to teach myself python from "How to Think Like a
Python Programmer" and have been trying to write a script that checks
'words.txt' for parameters (letters) given. The problem that is the i
can only get results for the exact sequnce of parameter 'letters'.
I'll spare posting all the different ways I've tried to search for
specific letters. But they are all generally:
for line in fin:
for linechar in line:
for ch in letters:
or the "for linechar in line:" and "for ch in letters:" get switched..
I'm getting really frustrated to say the least.
What alternative method could I use that isn't too advanced? Any
tips/suggestions on the code itself would be greatly appreciated, and
tips for learning in general.
here is the code that returns a certain sequence:
>>def searchtxt(lette rs):
fin = open('words.txt ')
words = ""
index = 0
count = 0
for line in fin:
index +=1
if letters in line.strip():
count += 1
words = line.strip() + '\n' + words
print words
print index, 'lines searched..', count, letters, 'words present'
Thank you in advance. 4 1306
Python Programmer" and have been trying to write a script that checks
'words.txt' for parameters (letters) given. The problem that is the i
can only get results for the exact sequence of parameter 'letters'.
The "re" module comes to mind:
text = open('words.txt ','r').read()
letters = 'sequence'
results = re.findall(lett ers,text)
result_count = len(results)
# one word per line:
for result in results :
print result
# one line
print ' '.join(results)
of course, you may need to invest a little time in regular expression
syntax to get exactly what you want, but I think you'll find that's
not wasted effort, as this is pretty standard and used in a lot of
other places.
Eric,
Thank you for helping.
Is the way I wrote the function inherently wrong? What I wrote
returns the sequence, however I'm trying to make the output match for
the letters in the string entered, not necessarily the string
sequence. For example if I search words.txt with my function for
'uzi' I get this:
>>searchtxt('uz i')
gauziest
gauzier
fuzing
fuzils
fuzil
frouziest
frouzier
defuzing
113809 lines searched.. 8 uzi words present
Only the sequence shows up 'uzi'. I don't get words like 'unzip' or
'Zurich' . I've only barely started on invocation and maybe writing
something like I'm describing is above what level I'm currently at.
On Apr 26, 2:20*pm, "Eric Wertman" <ewert...@gmail .comwrote:
*Python Programmer" and have been trying to write a script that checks
*'words.txt' for parameters (letters) given. *The problem that is the i
*can only get results for the exact sequence of parameter 'letters'.
The "re" module comes to mind:
text = open('words.txt ','r').read()
letters = 'sequence'
results = re.findall(lett ers,text)
result_count = len(results)
# one word per line:
for result in results :
* * print result
# one line
print ' '.join(results)
of course, you may need to invest a little time in regular expression
syntax to get exactly what you want, but I think you'll find that's
not wasted effort, as this is pretty standard and used in a lot of
other places.
On Sat, Apr 26, 2008 at 7:50 PM, <um******@gmail .comwrote:
ok.. I finally made something that works.. Please let me know what you
think:
>>def lines(letters):
fin = open('words.txt ')
count = 0
rescount = 0 # count the number of results
results = "" # there are words that contain the letters
for line in fin:
needs = 0
x = str(line.strip( ))
for ch in letters:
if ch not in x:
pass
else:
needs = needs + 1
if needs == len(letters):
rescount += 1
results = results + '\n' + x
count += 1
print count, 'lines searched'
print results, '\n'
print 'result count is: ', rescount
That's pretty much it.. I'm guessing you are assuming your file has
one word per line? I took a shot at it, without using the regex
module:
file = open('spyware')
my_string = 'uzi'
length = len(my_string)
words = []
for line in file :
chunks = line.strip().sp lit()
for chunk in chunks :
x = 0
for char in my_string :
x = chunk.rfind(cha r,x)
if x 0 :
words.append(ch unk)
print '\n'.join(words )
or with the re module:
import re
text = open('words.txt ').read()
pattern = '\S*u\S*z\S*i\S *'
stuff = re.findall(patt ern,text)
count = len(stuff)
print "Found %d words :" % (count)
print "\n".join(stuff )
En Sat, 26 Apr 2008 20:50:57 -0300, <um******@gmail .comescribió:
ok.. I finally made something that works.. Please let me know what you
think:
>>>def lines(letters):
fin = open('words.txt ')
count = 0
rescount = 0 # count the number of results
results = "" # there are words that contain the letters
for line in fin:
needs = 0
x = str(line.strip( ))
for ch in letters:
if ch not in x:
pass
else:
needs = needs + 1
if needs == len(letters):
rescount += 1
results = results + '\n' + x
count += 1
print count, 'lines searched'
print results, '\n'
print 'result count is: ', rescount
That's pretty good. Some improvements:
- The "natural" way to collect the results is using a list, appending words to it. Later you can print it one word per line or in any other format you want. Also, we don't need the "rescount" variable: it's just the length of the list.
needs = 0
for ch in letters:
if ch not in x:
pass
else:
needs = needs + 1
if needs == len(letters):
The overall idea is to test whether ALL letters are in the word `x`, ok? So as soon as we find a letter that isn't in the word, we are sure the test failed and we can break out of the loop. And if we get up to the last step, that means that all the letters were in the word (else we would not have got so far). So we don't have to count the letters; instead, we can use the "else" clause of the for loop (it means "the loop was exhausted completely".)
- I don't like the names "x" nor "ch"; I'm using "word" and "letter" instead. This is the revised version:
def lines(letters):
fin = open('words.txt ')
count = 0
results = [] # there are words that contain the letters
for line in fin:
word = line.strip()
for letter in letters:
if letter not in x:
break
else:
results.append( word)
count += 1
print count, 'lines searched'
print '\n'.join(resul ts), '\n'
print 'result count is: ', len(results)
That "\n".join(. ..) means "concatenat e all the items in the list using \n as a separator between items" and it's a pretty common idiom in Python.
--
Gabriel Genellina This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Ron Stephens |
last post by:
The newly rechristened Python Learning Foundation is a web site
dedicated to the assistance of people learning the Python programming
language. Features include:
1. Daily lists of new and recent Python-related web articles,
Sourceforge projects, and Vaults of Parnassus listings. These are
generated using Hans Nowak's Python web spider, mygale.py, and are
automatically updated each day. (You can visit Han's interesting blog
at <a href =...
|
by: post400 |
last post by:
Hi ,
I was just wondering ( yeah I know it's not the first time this
question pops up )
what would be the best 2 or 3 books for someone who wants to learn
Python , already experienced in other non-OOP languages .It takes time
to browse endlessly on the net , in a bookshop or a library for THOSE
books that are really useful !
Thanks ,
|
by: Ray |
last post by:
I want to jump in a learn Python. I have spent about a day looking at
editors and IDEs and (probably prematurely) selected jEdit to work in.
I have downloaded Python and jEdit. I have been going over jEdit for
a while and can't real see how to get it to know that I am using
Python.
So there is more there than I expected. Any suggestions on how to
configure (plugg-ins?) for jEdit and learn Python?
Ray
|
by: Falc |
last post by:
Hi there...
I have been looking at learning Python, so far it looks like an
absolutely grat language. I am having trouble finding some free
resources to learn Python from. I am on windows and the only experience
I have with programming is with PHP.
I have been trying to look at the free online book "Dive Into Python"
but this is far too difficult for me as it explains it in caparison
with C++ or Java.
|
by: Max |
last post by:
On monday I start a semester course in Python (the alternative was
Java). I was looking through the course outline and noticed the following:
1) UserDict is used. This is deprecated, right?
2) There is no mention of list comprehensions, but map and filter are
taught early and then revisited later. I don't think this is good: list
comprehensions are, IMO, one of Python's great features, Psyco prefers
them, they're more pythonic, and map...
| |
by: romiro |
last post by:
Hi all,
I'm a PHP5 developer looking to "broaden my horizons" so to speak by
learning a new language. I emphasize the 5 in PHP since I have fully
engrossed myself in the full OOP of version 5 with my own ground-up
projects as well as some work with PRADO (http://pradosoft.com)
I've dabbled with a number of languages in the past, Python being no
exception, but always ended up coming back to PHP due to being
comfortable with it. Python...
|
by: dogatemycomputer |
last post by:
Greetings,
A friend of mine dropped off a copy of Sams Teach Yourself Python in
24 Hours published in 2000. I skimmed the first couple of chapters
looking for the interpreter version and the book was based on version
Python version 1.5.
Is this book still relevant? Should I toss it and look for something
newer?
|
by: Rui Maciel |
last post by:
Recently I woke up inclined to take up the task of learning another
programming language. I've already dipped my toes in Perl (I've read online
tutorials and wrote a couple of irrelevant pet projects) but, as the
computers at my workplace only sport the python interpreter, it probably
means that learning python will end up serving me better, at least in the
short run. Plus, you know how Perl goes.
So far the decision seems to be a no...
|
by: John Salerno |
last post by:
Just something that crosses my mind every time I delve into "Learning
Python" each night. Does anyone see any value in learning Python when you
don't need to for school, work, or any other reason? I mean, sure, there's
value in learning anything at any time, but for something like a programming
language, I can't help but feel that I will be mostly unable to use what I
learn simply because I have no reason to use it.
The *process* of...
|
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: 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: 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: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
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: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |