[英]Find the number of \n before a given word in a long string
I have a long string:我有一个很长的字符串:
string = 'Idnum\rId\nkey: maturity\n2\nmaturity\rpara1\rpara2\n1Y\r0\r0\n2Y\r0\r0'
Now I want to find out the number of \\n
before the word \\nmaturity
(is unique in the string and we can see the answer is 2).现在我想找出单词\\nmaturity
之前的\\n
数量(在字符串中是唯一的,我们可以看到答案是 2)。
Here is the motivation of this question, if you cannot understand what I say below, just ignore it and focus on the question above.这是这个问题的动机,如果你不能理解我下面说的内容,请忽略它并专注于上面的问题。
I want to use pandas
to read the data
(I am not sure for the structure of data
, may be a csv):我想使用pandas
来读取data
(我不确定data
的结构,可能是一个csv):
and use the syntax:并使用语法:
value = pandas.read_csv(data, sep = '\t', skiprows = 3).set_index('maturity')
to skip first 3
rows before maturity
to obtain the table like:在maturity
前跳过前3
行以获得如下表:
So I need to find out the row number of maturity
to determine how many rows I should skip.所以我需要找出maturity
的行数来确定我应该跳过多少行。 But what I only know for data
is但我只知道data
是
data.getvalue() = 'Idnum\rId\nkey: maturity\n2\nmaturity\rpara1\rpara2\n1Y\r0\r0\n2Y\r0\r0'
( \\n
is changing the line and \\r
is changing the cell). ( \\n
正在更改行,而\\r
正在更改单元格)。 So I have to naively find the number of \\n
before maturity
to determine the row number of maturity
in the original table (or data
).所以我必须天真地找到maturity
前的\\n
数来确定原始表(或data
)中maturity
的行数。
So, if you are familiar with above structure, could you tell me how to find the row number of maturity
in the data
?那么,如果您熟悉上述结构,您能告诉我如何在data
找到maturity
的行数吗?
One way to do it:一种方法:
split
the string with '\\nmaturity' as separator and take the first (thus left of the first found item).首先使用 '\\nmaturity' 作为分隔符split
字符串并取第一个(因此位于第一个找到的项目的左侧)。count
to count the number of '\\n's.比使用count
来计算 '\\n' 的数量。Untested:未经测试:
string = 'Idnum\rId\nkey: maturity\n2\nmaturity\rpara1\rpara2\n1Y\r0\r0\n2Y\r0\r0'
stringUntilMaturity = string.split('\nmaturity')[0]
counts = stringUntilMaturity.count('\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.