473,385 Members | 1,958 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,385 software developers and data experts.

learning with python question (HtTLaPP)

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(letters):
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.
Jun 27 '08 #1
4 1290
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(letters,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.
Jun 27 '08 #2
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('uzi')
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(letters,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.
Jun 27 '08 #3
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().split()
for chunk in chunks :
x = 0
for char in my_string :
x = chunk.rfind(char,x)
if x 0 :
words.append(chunk)

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(pattern,text)
count = len(stuff)

print "Found %d words :" % (count)
print "\n".join(stuff)
Jun 27 '08 #4
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(results), '\n'
print 'result count is: ', len(results)

That "\n".join(...) means "concatenate all the items in the list using \n as a separator between items" and it's a pretty common idiom in Python.

--
Gabriel Genellina

Jun 27 '08 #5

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

Similar topics

5
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...
6
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...
4
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...
5
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...
7
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)...
5
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...
6
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...
6
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...
16
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?...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
marktang
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,...
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
Oralloy
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,...
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...

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.