首页 > 解决方案 > 从文件中读取字符串的特定区域

问题描述

我试图弄清楚如何用 python 做一些事情。我有一个文本文件,其中包含字符串,即:

M, 1, 14/08/2019 11:39, 4, xxxx, name, “Initialization of the system, and loading
M, 1, 14/08/2019 11:40, 100, xxxx, name, “Open Connection”
M, 1, 14/08/2019 11:40, 100, xxxx, name, “Close Connection, and reboot”
S, 1, 14/08/2019 11:40, 6, xxxx, name, We created the user in the systems
S, 1, 14/08/2019 11:41, 3, xxxx, User logged in, User tal logged in
M, 1, 14/08/2019 11:39, 4, xxxx, name, “Initialization of the system”
S, 1, 14/08/2019 11:40, 6, New User, We created the user in the systems
S, 1, 14/08/2019 11:41, 3, User logged in, User tal logged in
S, 1, 14/08/2019 11:42, 3, User logged in, User tal logged in
M, 2, 14/08/2019 11:43, 100, yyy, yura, 12345, Message

我想要做的是进入文件,如果它是第一次有 M,1 我应该打印一些文本,如果它的 S,1 或 M,2 或 S,1 相同。我还必须只打印文件中选定的行(还没有打印,但我会使用行计数器)。我还要做的是只打印选定的列,我所说的列是列之间有一个分隔符',',即如果我想打印第 1 行和第 2 行的 3 和 4 列,我应该只打印 14/ 08/2019 11:39 , 4 和 14/08/2019 11:40 , 100。我已经想出了如何用 re.split 拆分字符串,但我不知道如何继续。谢谢。

import re
import string
filename = '11.txt'
def infile(filename):
    m1 = m2 = s1 = s2 = 0
    linecounter = 1
    lines = [1,2,3]
    colums = [2,4]
    i=0
    fin = open(filename, 'r')
    if fin.closed:
        print ('file is closed')
    lines = fin.readlines()
    for line in lines:
        if(line[0] == 'M' and line[3] == '1' and m1 == 0):
            print('---M, 1, Datetime, Error Level, DeviceId, UserId, Message---\n')
            m1 = 1
        elif (line[0] == 'M' and line[3] == '2' and m2 == 0):
            print('---M, 2, Datetime, Error Level, DeviceId, UserId, MobileId, Message---\n')
            m2 = 1
        elif (line[0] == 'S' and line[3] == '1' and s1 == 0):
            print('---S, 1, Datetime, Error Level, DeviceId, Action, Message---\n')
            s1 = 1
        elif (line[0] == 'S' and line[3] == '2' and s2 == 0):
            print('---S, 2, Datetime, Error Level, DeviceId, IP, Action, Message---\n')
            s2 = 1
        for p in re.split(",",line): // thats a check of spliting, nothing else
            print("piece="+p)
        print(line)

infile(filename)

标签: pythonfilereadfile

解决方案


您可以使用字典来维护有关每行前缀第一次出现的信息,然后使用字典相应地打印信息。

此外,为每种类型(“M, 1”、“M, 2”等)及其标题维护一个映射将使打印最终结果变得更容易。

import json
from pprint import pprint
input_string = """M, 1, 14/08/2019 11:39, 4, xxxx, name, “Initialization of the system, and loading
M, 1, 14/08/2019 11:40, 100, xxxx, name, “Open Connection”
M, 1, 14/08/2019 11:40, 100, xxxx, name, “Close Connection, and reboot”
S, 1, 14/08/2019 11:40, 6, xxxx, name, We created the user in the systems
S, 1, 14/08/2019 11:41, 3, xxxx, User logged in, User tal logged in
M, 1, 14/08/2019 11:39, 4, xxxx, name, “Initialization of the system”
S, 1, 14/08/2019 11:40, 6, New User, We created the user in the systems
S, 1, 14/08/2019 11:41, 3, User logged in, User tal logged in
S, 1, 14/08/2019 11:42, 3, User logged in, User tal logged in
M, 2, 14/08/2019 11:43, 100, yyy, yura, 12345, Message"""


# Maintain mapping between the type of line, and the header corresponding to it
header_mapping = {"M, 1": ["Datetime", "Error Level", "DeviceId", "UserId", "Message"], 
    "M, 2":  ["Datetime", "Error Level", "DeviceId", "UserId", "MobileId", "Message"],
    "S, 1": ["Datetime", "Error Level", "DeviceId", "Action", "Message"],
    "S, 2": ["Datetime", "Error Level", "DeviceId", "IP", "Action", "Message"]
}
mapping = dict()

# Split the string into lines
lines = input_string.splitlines() 

for line in lines:
    split_line = line.split(", ") # Split each line using ", "
    key = split_line[0] + ", " + split_line[1] # First two elements of the split list form your key
    # Check if the key already exists. This is to ensure that our mapping dictionary contains only the first occurrence of each type.
    if not mapping.get(key, None):
        header = header_mapping[key]
        line_info = dict(zip(header, split_line[2:])) # Create dictionary with header-value mapping
        mapping[key] = line_info # Enter dictionary entry with type-values mapping

pprint(mapping)
"""
{'M, 1': {'Datetime': '14/08/2019 11:39',
          'DeviceId': 'xxxx',
          'Error Level': '4',
          'Message': '“Initialization of the system',
          'UserId': 'name'},
 'M, 2': {'Datetime': '14/08/2019 11:43',
          'DeviceId': 'yyy',
          'Error Level': '100',
          'Message': 'Message',
          'MobileId': '12345',
          'UserId': 'yura'},
 'S, 1': {'Action': 'name',
          'Datetime': '14/08/2019 11:40',
          'DeviceId': 'xxxx',
          'Error Level': '6',
          'Message': 'We created the user in the systems'}}

"""

推荐阅读