replace.if startwith('CERTAIN STRING')然后返回一个列表,可怕的标题

时间:2012-09-12 00:23:30

标签: python list dictionary replace startswith

example = ['1 Hey this is the first (1) level.\n', '2 This is what we call a second level.\n','','3 This is the third (3) level, deal with it.']
example = [i.rstrip() for i in example]

dictHeaders =   [['1 ','One'],
                ['2 ','Two'],
                ['3 ','Three'],
                ['4 ','Four'],
                ['5 ','Five'],
                ['6 ','Six']]

example = [eachLine.replace(old,new,1) if eachLine.startswith(old) for eachLine in article for old, newFront in dictHeaders]

我需要它返回......

example = ['One Hey this is the first (1) level.', 'Two This is what we call a second level.','','Three This is the third (3) level, deal with it.']

我创建了dictHeaders作为列表列表,原因是为每个实例的每个键添加移动值。例如,如果eachLine.startswith(old)然后将One附加到开头,则可能将另一个字符串附加到该行的末尾。如果我能用dict完成上述操作,我宁愿走那条路。我是Python的新手。

我认为这是要走的路而不是......

def changeCode(example,dictHeaders):
    for old, newFront in dictHeaders:
        for eachLine in example:
            if eachLine.startswith(old):
            return eachLine.replace(old,newFront,1)

每次我运行上面它只返回顶行,但我需要它返回整个列表example修改..

2 个答案:

答案 0 :(得分:1)

最好的方法是使用正则表达式并智能地替换数字:

import re

examples = [
  '1 Hey this is the first (1) level.\n',
  '2 This is what we call a second level.\n',
  '3 This is the third (3) level, deal with it.',
  '56 This is the third (3) level, deal with it.'
]

class NumberReplacer(object):
  def __init__(self):
    self.ones = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
    self.teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
    self.tens = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']

  def convert(self, number):
    if number == 0:
      return 'zero'
    elif number < 10:
      return self.ones[number - 1]
    elif number <= 19:
      return self.teens[number % 10]
    else:
      tens = self.tens[number // 10 - 2]
      ones = number % 10 - 1

      if ones == -1:
        return tens
      else:
        return ' '.join([tens, self.ones[ones]])

  def __call__(self, match):
    number = int(match.group(0))

    return self.convert(number).title()

replacer_regex = re.compile('^\s*(\d+)')
replacer = NumberReplacer()

for example in examples:
  print replacer_regex.sub(replacer, example)

答案 1 :(得分:0)

你很亲密。你不应该从for循环内部返回。相反,您可以创建list作为返回值并将每个结果附加到其中

def changeCode(example,dictHeaders):
    retval = []
    for eachLine in example:
        for old, newFront in dictHeaders:
            if eachLine.startswith(old):
                retval.append(eachLine.replace(old,newFront,1))
                break
        else:
            retval.append(eachLine)
    return retval