[英]How to extract text part from file using Python & Regular Expressions
[英]How to find and count each line in a text file using regular expressions in python?
我有一个文本文件,其中包含:
motion
black
lotion
mansion
cardio
sensational
我将如何使用正则表达式来打印所有包含“ ion”的单词? 因此它打印:
motion
lotion
mansion
sensational
当它打印时,我需要它不以字符串形式打印单词,因此它看起来像:
motion
不
"motion"
到目前为止,我的代码是:
import re
f = open("file.txt","r")
ex = re.findall("", f)
print ex
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)
出:
motion
lotion
mansion
sensation
您可以使用filter
执行此操作。
获得所有行的列表后,请使用以下内容:
def f(line):
return re.match(r'ion', line)
matches = filter(f, all_lines)
列表matches
将包含all_lines
中包含“ ion”的行的子集
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.