Python:如何对fi中的每个整数加1

2024-09-27 07:31:26 发布

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

我有一个脚本,其中包含与字典中匹配键相关的索引。最近的一个变化要求我将所有数字移到1以上(每个数字加1)。例如,如果文件要包含以下内容:

form['formA'] = {
  'title': 'titleA',
  'number': 3,
  'numbers': [1,2,4,5]
}

form['formB'] = {
  'title': 'titleB',
  'number': 7,
  'numbers': [8,9,10,11]
}

我希望每个整数都大一个。所以它会变成:

^{pr2}$

在所有的类型错误,属性错误,以及仅仅破坏格式化的情况下,我不知道如何做到这一点。以下是我最接近的尝试:

#read from the file
f = open(currdir, 'r')
content = f.readlines()
f.close()

addbrackets = False    #is it a list
for line in content:
    if "form" not in line:
        #grab only the values to the right of the colon
        rightside = line.split(":")[-1]
        list_of_nums = rightside

        #remove brackets
        if "[" in rightside:
            addbrackets = True
            removebrackets = rightside.replace("[","").replace("]","")
            list_of_nums = removebrackets.split(",")

        #search for all integers in the list and add 1
        for num in list_of_nums:
            if type(num) is int:
                num += 1
                numindex = list_of_nums.index(num)
                list_of_nums[numindex] = num

        #plug new values into content
        lineindex = content.index(line)
        if addbrackets:
            content[lineindex] = line.replace(rightside, "[" + ",".join(list_of_nums))[:-1] + "],"
            addbrackets = False
        else:
            content[lineindex] = line.replace(rightside, "".join(list_of_nums))

#write to the new file
f = open(newdir, 'w')
f.write("".join(content))
f.close()

然而,这只会把格式搞乱。有办法吗?在

谢谢。在


Tags: oftheinformforiflinecontent
2条回答

使用正则表达式:

foo="""
form['formA'] = {
  'title' = 'titleA',
  'number' = 3,
  'numbers' = [1,2,4,5]
}

form['formB'] = {
  'title' = 'titleB',
  'number' = 7,
  'numbers' = [8,9,10,11]
}
"""

def incNumbers(s):
  def inc(m):
    return str(int(m.group())+1)
  return re.sub(r'(\d+)', inc, s)


def go(m):
  return m.group(1) + incNumbers(m.group(2))

r = re.compile('^( *\'numbers?\' =)(.*)', re.MULTILINE)
print re.sub(r, go, foo)

如果你真的想保留格式,并且想对你重新格式化的内容不加区分(例如,所有的整数都被单词边界隔开),那么这是一个简单的正则表达式搜索/替换,你需要搜索一个单词边界(\b),任意数量的连续整数(\d+),然后是终止字边界(\b)。这将使'foo 15 bar''[1]''[1, 2]'等字符串中的数字递增,而不是'foo15bar'或{}:

import re
with open(yourfilename) as fin:
  s = fin.read()
print re.sub(r'\b\d+\b', lambda m: str(int(m.group())+1), s)

如果我将您的数据作为一个字符串分配给s,然后运行最后一行,我得到:

^{pr2}$

这似乎是你想要的。当然,如果你有一些不想递增的数字,那么这就行不通了,你需要一种更聪明的方法来解析文件。在

相关问题 更多 >

    热门问题