I have a text file and I want to display all words that contains both z and x characters.
How can I do that ?
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
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
>>> 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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With