Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display all words that contain these characters?

Tags:

python

I have a text file and I want to display all words that contains both z and x characters.

How can I do that ?

like image 591
xRobot Avatar asked Oct 18 '10 19:10

xRobot


3 Answers

If you don't want to have 2 problems:

for word in file('myfile.txt').read().split():
    if 'x' in word and 'z' in word:
        print word
like image 191
Wooble Avatar answered Nov 15 '22 06:11

Wooble


Assuming you have the entire file as one large string in memory, and that the definition of a word is "a contiguous sequence of letters", then you could do something like this:

import re
for word in re.findall(r"\w+", mystring):
    if 'x' in word and 'z' in word:
        print word
like image 34
Tim Pietzcker Avatar answered Nov 15 '22 06:11

Tim Pietzcker


>>> import re
>>> pattern = re.compile('\b(\w*z\w*x\w*|\w*x\w*z\w*)\b')
>>> document = '''Here is some data that needs
... to be searched for words that contain both z
... and x.  Blah xz zx blah jal akle asdke asdxskz
... zlkxlk blah bleh foo bar'''
>>> print pattern.findall(document)
['xz', 'zx', 'asdxskz', 'zlkxlk']
like image 32
Steven Rumbalski Avatar answered Nov 15 '22 06:11

Steven Rumbalski