查找长字符串中给定单词前的\n数字

2024-10-08 18:28:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根长长的绳子:

string = 'Idnum\rId\nkey: maturity\n2\nmaturity\rpara1\rpara2\n1Y\r0\r0\n2Y\r0\r0'

现在我想找出单词\n前面的\nmaturity的数字(在字符串中是唯一的,我们可以看到答案是2)

这是这个问题的动机,如果你不能理解我下面说的话,就忽略它,把注意力集中在上面的问题上

我想使用pandas来读取data(我不确定data的结构,可能是csv):

enter image description here

并使用以下语法:

value = pandas.read_csv(data, sep = '\t', skiprows = 3).set_index('maturity') 

跳过3前的maturity行以获得如下表: enter image description here

所以我需要找出maturity的行号来决定我应该跳过多少行。但我只知道data

data.getvalue() = 'Idnum\rId\nkey: maturity\n2\nmaturity\rpara1\rpara2\n1Y\r0\r0\n2Y\r0\r0'

\n正在更改行,\r正在更改单元格)。因此,我必须天真地在maturity之前找到\n的数目,以确定原始表中maturity的行数(或data

所以,如果你熟悉上面的结构,你能告诉我如何在data中找到maturity的行号吗


Tags: csvpandasdata结构r0n2ridmaturity
1条回答
网友
1楼 · 发布于 2024-10-08 18:28:07

一种方法是:

  • Firstsplit以'\nmaturity'作为分隔符的字符串,并取第一个(因此位于找到的第一个项的左侧)
  • 然后使用count来计算'\n'的数目

未经测试:

string = 'Idnum\rId\nkey: maturity\n2\nmaturity\rpara1\rpara2\n1Y\r0\r0\n2Y\r0\r0'
stringUntilMaturity = string.split('\nmaturity')[0]
counts = stringUntilMaturity.count('\n')

相关问题 更多 >

    热门问题