Python:需要根据文本字符串中的2个或多个匹配项输出到文件

时间:2014-01-14 14:10:50

标签: python scripting

我是Python新手,我正在尝试根据文本文件的两个条件找到写入文件的方法:

  1. 在给定文本中,其中一行必须与我的搜索完全匹配。位置和价值始终相同。

  2. 如果满足上述条件1并且X值(要定义\可以更改)也存在于已知位置的文本中,则打印条件1中的匹配文本和值X 10个直接进行中从不改变的角色。

  3. 所以,从我在本网站上看到的另一个例子中给出的文字:

    textInput = """\
    I'm trying to have my program grab every fifth word from a text file and
    place it in a single string. For instance, if I typed "Everyone likes to
    eat pie because it tastes so good plus it comes in many varieties such
    as blueberry strawberry and lime" then the program should print out
    "Everyone because plus varieties and." I must start with the very first
    word and grab every fifth word after. I'm confused on how to do this.
    Below is my code, everything runs fine except the last 5 lines."""
    

    从这个例子中,我想写一个文件如下,但只有两者都存在:

    "place it in a single string. For instance, if I typed "Everyone likes to" 
    

    "blueberry strawberry and lime"

    石灰这个词可能会变成一个未知的,变化的值。

    归结为我有一堆我正在经历的日志文件。如果文件中的特定位置存在IP地址,我希望该IP(未知),10个前进字符以及始终存在于IP几行的文本字符串。这两个都要写入文件。

    我弄清楚如何打开\关闭文件和写入条目等到特定找到短语的新文件,但是如果满足两个或更多条件的特定组合,则在将条目发送到文件时遇到问题。

1 个答案:

答案 0 :(得分:0)

我认为最好的方法是读取日志文件,然后使用正则表达式查找日志中的所有IP地址。

ip = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
ip = re.findall(ip, yourLogFile)

然后你会使用os循环遍历已经在文件中的ip文件夹中的每个文件

import os

ipAlreadyOnFile = []
for root, dirs, files in os.walk(r'C:\yourDirectory'):
    for file in files:
        ipAlreadyOnFile.append(file)

然后你可以找到两个列表之间的差异:

newIp = list(set(ip) - set(ipAlreadyOnFile))

现在你的newIp列表只有新的ip地址,无论是添加到你的目录还是做其他事情。