Skip to main content
 首页 » 编程设计

python之如何在 python 中使用正则表达式查找和计算文本文件中的每一行

2024年08月21日30lori

我有一个文本文件,其中包含:

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