【问题标题】:Find the number of \n before a given word in a long string在长字符串中查找给定单词之前的 \n 数量
【发布时间】:2019-01-21 15:07:34
【问题描述】:

我的字符串很长:

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

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

这里是这个问题的动机,如果你不能理解我在下面说的内容,请忽略它并专注于上面的问题。

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

并使用语法:

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

maturity 之前跳过第一个3 行以获得如下表:

所以我需要找出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的行号吗?

【问题讨论】:

    标签: python string pandas


    【解决方案1】:

    一种方法:

    • 首先split 以'\nmaturity' 作为分隔符的字符串并取第一个(因此在第一个找到的项目的左侧)。
    • 比使用count 来计算'\n's 的数量。

    未经测试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-28
      • 2021-05-23
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 2016-05-28
      相关资源
      最近更新 更多