0
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)then 附加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修改..

4

2 回答 2

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)
于 2012-09-12T00:33:09.887 回答
0

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

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
于 2012-09-12T02:02:06.603 回答