I have a text file that contains:
我有一个文本文件包含:
motion
black
lotion
mansion
cardio
sensational
How would I use a regular expression to print all the words that contain 'ion'? So it prints:
如何使用正则表达式打印包含“ion”的所有单词?所以它打印:
motion
lotion
mansion
sensational
When it prints I need it to print the word not in a string so it looks like:
当它打印时,我需要它打印单词而不是字符串,所以它看起来像:
motion
not
不
"motion"
The code I have so far is:
到目前为止,我的代码是:
import re
f = open("file.txt","r")
ex = re.findall("", f)
print ex
3 个解决方案
#1
1
import re
# file = open('filename').read()
file = '''
motion
black
lotion
mansion
cardio
sensational '''
matchs = re.findall(r'.+ion.*?', string=file)
for word in matchs:
print(word)
out:
:
motion
lotion
mansion
sensation
#2
1
You can do this using a filter
.
您可以使用过滤器来实现这一点。
Once you have a list of all the lines, use something like the following:
一旦你列出了所有的行,使用如下的方法:
def f(line):
return re.match(r'ion', line)
matches = filter(f, all_lines)
The list matches
will contain the subset of the lines in all_lines
which contain 'ion'
列表匹配将包含all_lines的子集,其中包含“ion”
#3
1
import re
with open('file.txt') as f:
for line in f.read().split('\n'):
if re.search(r'ion', line):
print line
Output :
motion
lotion
mansion
sensational
#1
1
import re
# file = open('filename').read()
file = '''
motion
black
lotion
mansion
cardio
sensational '''
matchs = re.findall(r'.+ion.*?', string=file)
for word in matchs:
print(word)
out:
:
motion
lotion
mansion
sensation
#2
1
You can do this using a filter
.
您可以使用过滤器来实现这一点。
Once you have a list of all the lines, use something like the following:
一旦你列出了所有的行,使用如下的方法:
def f(line):
return re.match(r'ion', line)
matches = filter(f, all_lines)
The list matches
will contain the subset of the lines in all_lines
which contain 'ion'
列表匹配将包含all_lines的子集,其中包含“ion”
#3
1
import re
with open('file.txt') as f:
for line in f.read().split('\n'):
if re.search(r'ion', line):
print line
Output :
motion
lotion
mansion
sensational