繁体   English   中英

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

[英]How to search text file line by line for '/##/'?

我试图逐行搜索文本文件,如果一行包含/ ## /格式,我想打印该行。 我知道我要的行将采用这种格式,因为我正在尝试提取日期。 是否有类似这样的语法? 例如..

 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

提取行后,就可以使用正则表达式在/的前面/后面搜索数字。 谢谢。

您可以使用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)

你走近了! \\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,这会调用您脚本的迷你版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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