Get line index python

How can I get the line of index + 1 when enumerating lines in Python

Question: Consider the following string: How to get a character in any position (>=0) with a related column and line? position means put all the characters in a row and then count them from zero like: Solution 1: Split the string in to lines: Then you can access for example the 3rd line and the 4th column via (Assuming you start counting at zero) So all you need is to split the file content by new line and iterate over the lines to find the date like so:

How can I get the line of index + 1 when enumerating lines in Python

I am reading through the lines of a file using the code for index, line in enumerate(lines): . I can access the string of the current line using (line).

Is it possible to access the next line to look ahead? I have tried to access this by using next_line = line(index + 1) but this is creating an error.

with open(sys.argv[1]) as f1: with open(sys.argv[2], 'a') as f2: lines = f1.readlines() prev_line = "" string_length = 60 for index, line in enumerate(lines): next_line = line(index + 1) print(f'Index is ') # Do something here 

line is a string therefore you can not do what you need. Try something like this:

with open(sys.argv[1]) as f1: with open(sys.argv[2], 'a') as f2: lines = f1.readlines() prev_line = "" string_length = 60 for index, line in enumerate(lines): try: next_line = lines[index + 1] except IndexError: pass print(f'Index is ') # Do something here 

You can just access it from the list as you normally would, this will cause an exception on the last iteration so I added a check to prevent this:

with open(sys.argv[1]) as f1: with open(sys.argv[2], 'a') as f2: lines = f1.readlines() prev_line = "" string_length = 60 for index, line in enumerate(lines): if index < ****(lines) - 1: next_line = lines[index+1] print(f'Index is ') # Do something here 

Python Program to Get Line Count of a File, Using a for loop, iterate through the object f . In each iteration, a line is read; therefore, increase the value of loop variable after each iteration. Example

Читайте также:  Python string data type

The "Get on the line" Coach

The Get On The Line Coach 2

The Get On The Line Coach On Homecoming

How to get line and column by position in C#?

Consider the following string:

var text = @" Hello How Are You doing? ""MyNameIs:"" XYY "; 

How to get a character in any position (>=0) with a related column and line?

position means put all the characters in a row and then count them from zero like:

\n \n \n **** o ' ' H o w \n A r e . 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 . 
public CharInfo GetCharInfo(int position) // for example position 35 < // . return new CharInfo(char, line, column); >

Split the string in to lines:

Then you can access for example the 3rd line and the 4th column via

(Assuming you start counting at zero)

EDIT : After you updated your question, this code might help you:

int position = 35; string[] lines = text.Split('\n'); int lineIndex = 0; int columnIndex = 0; foreach(string line in lines) < if(position < line.Length) < columnIndex = position; break; >else < position -= line.Length + 1; // +1 because split removes the \n >lineIndex++; > Console.WriteLine("line="+lineIndex); Console.WriteLine("column="+columnIndex); Console.WriteLine("char="+text[position]); 

This gives you the character, its line and its column at position 35.

 int indexToSearchfor = 35; string subString = text.Substring(0, indexToSearchfor); int line = subString.Count(c=> c == '\n'); // Count the number of line breaks int row = subString.Length - subString.LastIndexOf('\n')-1; //Calculate number of chars since last line break, adjust of off-by-one error Console.WriteLine(line); Console.WriteLine(row); 

Edit: updated after AlexandruClonțeas comment regarding performance

Linq will almost never be the most optimized solution but really helps with readability. If we're concerned with performance, Span is great help.

ReadOnlySpan text = Text.AsSpan().Slice(0,pos); var e = text.GetEnumerator(); int r=0,c=0,n=0; while(e.MoveNext()) < if(e.Current == '\n')< r++; c=n; >n++; > return(r,pos-c-1); 

Comparing this to my original answer using Linq and AlexandruClonțeas solution, woring on a 10Mb input file we get:

// * Summary * BenchmarkDotNet=v0.12.1, OS=Windows 10.0.18363.900 (1909/November2018Update/19H2) Intel Core i7-7700 CPU 3.60GHz (Kaby Lake), 1 CPU, 8 logical and 4 physical cores .NET Core SDK=3.1.201 [Host] : .NET Core 3.1.3 (CoreCLR 4.700.20.11803, CoreFX 4.700.20.12001), X64 RyuJIT DefaultJob : .NET Core 3.1.3 (CoreCLR 4.700.20.11803, CoreFX 4.700.20.12001), X64 RyuJIT | Method | Mean | Error | StdDev | |--------------- |------------:|----------:|----------:| | TestWithLinq | 44,091.1 us | 649.20 us | 575.50 us | | TestWithSpan | 660.6 us | 11.95 us | 9.98 us | | GetCharFromPos | 1,747.4 us | 21.54 us | 17.99 us | // * Hints * Outliers Test.TestWithLinq: Default -> 1 outlier was removed (46.93 ms) Test.TestWithSpan: Default -> 2 outliers were removed (703.07 us, 703.25 us) Test.GetCharFromPos: Default -> 4 outliers were removed (1.84 ms..2.87 ms) 

Full gist can be found here: https://gist.github.com/JC-85/44a7ce76de6fba72c1dc1d028b9b2abc

Conslusion: Comparatively Linq is pretty slow, but processing a 10Mb file still takes less than 50ms. If performance still is an issue for some reason, use Span.

Edit Speaking of optimizations, we should realize were aproaching the problem from the wrong direction. Starting from zero and counting up we need to keep track of both row and column since we don't know if we've passed the last line-break until we reach the the target pos.

If we instead start from target pos and move backwards, then we only need to keep track of column until we reach the nearest line break, after that we only need to increment the row-count until we reach the beginning.

private static unsafe (int, int) AreWeDoneYet (string text, int pos) < int row = 0; int col = 0; fixed (char * p = text) < var p1 = p + pos; while ( * p1-- != '\n') col++; while (p1 >= p) < if ( * p1-- == '\n') row++; >> return (row, col); > 

The simplest and most efficient solution (in terms of memory and performance) which can also be easily adapted to streams rather than strings for large inputs:

 private static (int line, int column, char chr) GetCharFromPosition(string text, int pos) < var line = 0; var col = 0; for (int i = 0; i else < col++; >> return (line, col, text[pos]); > 

Update after performance comparison. If you are that concerned with performance, and this is run on an in-memory string, this would be the way to go:

private static unsafe (int line, int column, char chr) GetFromPosUnsafe(string text, int pos) < var line = 0; var col = 0; char c = '\0'; char returnedChar = '\0'; int strLength = text.Length; fixed (char* p = text) < var p1 = p; for (int i = 0; i < pos; i++) < c = *p1++; if (c == '\n') < line++; col = 0; >else < col++; >returnedChar = c; > > return (line, col, returnedChar); > 

The easiest and complete answer

public class CharLocation < public CharLocation(char character, int line, int column) < Line = line; Column = column; Character = character; >public int Line < get; private set; >public int Column < get; private set; >public char Character < get; private set; >> public static CharLocation GetCharLocation(this string text, int position)

Get in Line - Simon Curtis [HQ] (Full Song), From Simon Curtis' sophomore album - RA [2011]I DO NOT OWN ANY OF THIS; NO Duration: 3:45

Get line of file content that contain a string

I wanted to get line content in a file that contains a string in discord js node.

like, if one of the lines in the file contains the string. It's gonna send the line that contains the string to the console.

So all you need is to split the file content by new line and iterate over the lines to find the date like so:

const testFolder = './logs/Chatlogs'; const fs = require('fs'); const path = require('path'); fs.readdirSync(testFolder).forEach(file => < console.log(file); // read the file content var content = fs.readFileSync(path.join(testFolder, file)); var date = '20211203'; var lines = content.split('\n'); lines.forEach(l => < if(l.indexOf(date) >-1) console.log('Found it:', l); >); >); 

The Get On The Line Coach On Homecoming, If you lose on Homecoming “GET ON THE LINE. ” Duration: 3:12

Источник

Оцените статью