-1

我有一个文本文件,比如说

1: 0,0,0,122
2: 2,0,3,333
3: 0,0,0,23

等等。我需要在文本文件中找到“0,0,0”模式并打印除包含给定模式的行之外的所有行。请谁能告诉我python中的代码

4

3 回答 3

6

一个健壮的方法是这样的:

import re
pattern = re.compile(r'0\s*,0\s*,0\s*')
with open(filename) as f:
    for line in f:
            if pattern.search(line):
                    print line

这样,如果您有一行有一些空间,它就会被跳过(例如“0, 0,0”而不是“0,0,0”)。

但是如果你确定不会有这样的事情,或者如果你想完全匹配“0,0,0”[无空格],那么你可以避免使用re模块而只使用in运算符:

with open(filename) as f:
    for line in f:
            if '0,0,0' not in line:
                    print line
于 2012-08-31T09:26:51.883 回答
0
for line in textfile.split('\n'):
    if '0,0,0' not in line:
        print line
于 2012-08-31T09:20:58.547 回答
0

使用上下文管理器打开文件。逐行遍历文件。如果您的模式没有出现在该行中,请打印该行:

filename = 'textfile.txt'
pattern = '0,0,0'

with open(filename) as f:
    for line in f:
        if pattern not in line:
            print line

未经测试,但应该可以工作。

于 2012-08-31T09:21:23.263 回答