Create Sections in Python

2024/10/8 12:41:46

I am newbie to Python. I have large file with repetitive string through the logs

Example:

abc
def
efg
gjk
abc
def
efg
gjk
abc
def
efg
gjk
abc
def
efg
gjk

Expected Result

--------------------Section1---------------------------
abc
def
efg
gjk
--------------------Section2---------------------------
abc
def
efg
gjk
--------------------Section3---------------------------
abc
def
efg
gjk
--------------------Section4---------------------------
abc
def
efg
gjk

Could some provide me pointers to proceed with this. I tried grep for the particular string, it gives me only the string in particular order. I want the entire log from abc to gjk put in a section.

Answer

If a section is defined by the starting line, you can use a generator function to yield sections from an input iterable:

def per_section(iterable):section = []for line in iterable:if line.strip() == 'abc':# start of a section, yield previousif section:yield sectionsection = []section.append(line)# lines done, yield lastif section:yield section

Use this with an input file, for example:

with open('somefile') as inputfile:for i, section in enumerate(per_section(inputfile)):print '------- section {} ---------'.format(i)print ''.join(section)

If sections are simply based on the number of lines, use the itertools grouper recipe to group the input iterable into groups of a fixed length:

from itertools import izip_longestdef grouper(iterable, n, fillvalue=None):"Collect data into fixed-length chunks or blocks"# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxxargs = [iter(iterable)] * nreturn izip_longest(fillvalue=fillvalue, *args)with open('somefile') as inputfile:for i, section in enumerate(grouper(inputfile, 4, '\n')):print '------- section {} ---------'.format(i)print ''.join(section)
https://en.xdnf.cn/q/118699.html

Related Q&A

Process CSV files in Python - Zero Imports/No Libraries

I have CSV example like this ID,TASK1,TASK2,QUIZ1,QUIZ2 11061,50,75,50,78 11062,70,80,60,50 11063,60,75,77,79 11064,52,85,50,80 11065,70,85,50,80how do i get the Max, Min and Avg on specific Column? i…

python - debugging: loop for plotting isnt showing the next plot

I need help in debugging. I just cant figure out why its not working as expected.The Code below should read data files (names are stored in all_files) in chunks of 6, arrange them in subplots (i,j indi…

Return formatted string in Python

I have a string:testString = """ My name is %s and I am %s years old and I live in %s"""I have code that finds these three strings that I want to input into testString. Ho…

How to get the greatest number in a list of numbers using multiprocessing

I have a list of random numbers and I would like to get the greatest number using multiprocessing. This is the code I used to generate the list: import random randomlist = [] for i in range(100000000):…

python pandas yahoo stock data error

i am try to pullout intraday aapl stock data by yahoo. but there problem i facing with my program..import pandas as pd import datetime import urllib2 import matplotlib.pyplot as plt get = http://chart…

Web Scraping Stock Ticker Price from Yahoo Finance using BeautifulSoup

Im trying to scrape Gold stock ticker from Yahoo! Finance. from bs4 import BeautifulSoup import requests, lxmlresponse = requests.get(https://finance.yahoo.com/quote/GC=F?p=GC=F) soup = BeautifulSoup(…

How to convert the radius from meter to pixel?

I have a camera with these specs:full resolution 1280x1024 pixel size 0.0048mm focal length 8 mmI need to detect a ball in this image. It is 4 meters away and its radius is 0.0373 meter. How to convert…

Calculting GPA using While Loop (Python)

A GPA, or Grade point Average, is calculated by summing the grade points earned in a student’s courses and then dividing by the total units. The grade points for an individual course are calculated by…

Return function that modifies the value of the input function

How can I make a function that is given a function as input and returns a function with the value tripled. Here is some pseudo code for what Im looking for. Concrete examples in Python or Scala would b…

how to access the list in different function

I have made a class in which there are 3 functions. def maxvalue def min value def getActionIn the def maxvalue function, I have made a list of actions. I want that list to be accessed in def getaction…