如何逐行搜索文本文件' / ## /'?

时间:2017-09-26 02:03:32

标签: regex python-3.x if-statement line enumerate

我试图逐行搜索文本文件,如果一行包含/ ## / format,我想打印该行。我知道我想要的行会有这种格式,因为我试图提取日期。有这样的语法吗?例如..

 if('/%d%d/' in line):
    print (line)

在两个正斜线之间是否可以使用相当于0-9的数字?我在逐行搜索文件时没有问题,这是我的代码:

items = os.listdir("C:/output3")
for names in items:
    if names.endswith(".txt"):
        with open('C:/output3/' + names) as currentFile:
            for i, line in enumerate(currentFile):
                line=line.rstrip()
                if('/%d%d/' in line):
                    print (line)
                else:
                    i = i + 1

一旦我可以提取该行,我就可以使用正则表达式来搜索/' s前面/后面的数字。感谢。

2 个答案:

答案 0 :(得分:0)

您可以使用re包。 它提供了函数searchmatch,它们接收模式和字符串作为参数。

search(pattern, string, flags=0)
    Scan through string looking for a match to the pattern, returning
    a match object, or None if no match was found.


match(pattern, string, flags=0)
    Try to apply the pattern at the start of the string, returning
    a match object, or None if no match was found.

在下面的示例中,我假设您希望获得包含斜杠的任意两个数字,例如/12//45/。如果您不想匹配斜杠,只需删除它们即可。

我选择使用\d两次作为两个数字的模式,但它可以是任何其他等效的正则表达式。

# Importing regex package
import re

# Your code here...

# Define a pattern to match
pattern = '/\d\d/'

# Check if re.search() returns an object
if re.search(pattern, line) is not None:
    print(line)

答案 1 :(得分:0)

你走近了! \d序列与数字(0-9)匹配。以下是如何在脚本的正则表达式中使用它:

import re 
...
if re.match('\d\d', line) is not None 
    print(line)

re.match匹配字符串的开头,因此我们不需要像使用其他语言那样使用^锚点。如果我们不想从头开始匹配,我们可以使用re.search

我们也可以通过简单地检查该行的前两个字符是否为数字来避免使用正则表达式:

if line[:2].isdigit() 
    print(line) 

[:2]从字符串的开头获取一个长度为2的子字符串。

以上是您可以直接从命令行使用的实现:

type C:\output3\*.txt | python -c 'import sys;[[sys.stdout.write(line)] for line in sys.stdin if line.rstrip()[:2].isdigit()]'

type是Windows中的内置命令。我们只是在这里使用它来获取该目录中任何 .txt 文件的内容。然后我们将type的输出传递给python,它会调用脚本的迷你版本。