1

Suppose I have a text file where each line contains either '1' or '-1.' How do I search through the file to check if the file contains at least one '1'?

Initially, I had the following.

if re.search(r'\b1', f.read()): return true
else: return false

However, this does not work because '-' is not considered an alphanumeric string and returns true if the file does not contain a single '1.' What is the best way to determine if the file contains '1'?

4

6 に答える 6

1

any('1' in line for line in file)ファイル全体をメモリに読み込まない1つの方法です。

複雑だがおそらく効率的な方法

fmap = mmap.mmap(open('file').fileno(), 0)
'1' in fmap

mmapされたファイルに対してreを実行することもできます。

re.search('^1', fmap, re.M)
于 2012-07-10T15:37:50.123 に答える
1

re.MULTILINEフラグを使用すると、 ^(件名の先頭だけでなく)行の先頭に一致します。

re.search(re.compile('^1', re.MULTILINE), f.read())

これは、行が。で始まる場合に一致し1ます。

http://docs.python.org/library/re.html#regular-expression-syntaxを参照してください


この代替ソリューションは、ファイルを完全に読み取ることを避けます。

has_1 = any(line == "1" for line in f)
于 2012-07-10T15:22:45.217 に答える
1


f = open("textfile.txt", "rb")
lines = f.readlines()
new_lines = [line.replace("-1", "") for line in lines]
for line in new_lines:
    if "1" in line:
        print "Damn right!"
        break

于 2012-07-10T15:48:21.600 に答える
0
def thingy(contents):
    return any(line.strip() == "1" for line in contents.splitlines())

thingy("1\n-1\n-1") # True
thingy("-1\n-1\n-1") # False

または:

def thingy(contents):
    for line in contents.splitlines():
        if line.strip() == "1":
            return True

    return False
于 2012-07-10T15:25:51.217 に答える
0


単にリスト内包表記で:

>>> if not None in [ re.search( r"1", line ) for line in f.readlines() ] :
        pass # <your code here>
于 2012-07-10T22:39:30.813 に答える
0

「1」または「-1」が常に行の先頭にある場合は、正規表現を次のように変更できます。

 ^1

それらが常に行の中央/端にある場合は、次を使用します。

[^-]1

それらが最初に発生することもあれば、中間/終了時に発生することもある場合は、次のようなことを試してみてください。

^1|[^-]1

私はこれらをテストしていません。特に最後のものは、優先順位が正しいかどうかわかりません。

于 2012-07-12T11:37:09.487 に答える