如何显示包含这些字符的所有单词?
我有一个文本文件,我想显示里面所有同时包含字母 z 和 x 的单词。
我该怎么做呢?
7 个回答
4
>>> 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']
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。
8
假设你把整个文件都存储在内存中,作为一个很大的字符串,并且我们把“单词”的定义理解为“一串连续的字母”,那么你可以这样做:
import re
for word in re.findall(r"\w+", mystring):
if 'x' in word and 'z' in word:
print word
13
如果你不想遇到两个问题:
for word in file('myfile.txt').read().split():
if 'x' in word and 'z' in word:
print word