繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM