【问题标题】:Arithmetic operations in notepad using a python script使用 python 脚本在记事本中进行算术运算
【发布时间】:2019-05-10 17:22:44
【问题描述】:

有一个这种类型的数据库。

数据库.ini:

[1 StatsObject]
InfoStat=1

[2 StatsObject]
InfoStat=2

etc.

InfoStat 值需要乘以特定的修饰符。

我在notepad++中使用了python脚本

import re

FixedStat = 0
StatMod = 20
Result = 0
FixedStatStr = ""

content = editor.getText()
for row, line in enumerate(content.split('\n')):
    for m in re.finditer(r'InfoStat=[0-9]+', line):
        if(int(m.group(0).split('=').pop()) > 0):
            FixedStat = int(m.group(0).split('=').pop())
            Result = FixedStat * StatMod
            FixedStatStr = 'InfoStat=' + str(Result)
            content = re.sub(m.group(0), FixedStatStr, content)
            editor.setText(content)

预期结果:

[1 StatsObject]
InfoStat=20

[2 StatsObject]
InfoStat=40

实际结果:

[1 StatsObject]
InfoStat=400

[2 StatsObject]
InfoStat=40

我想在将 1 转换为 20 之后, 在将 2 转换为 40 期间, 20也在变化, 因为:

m.group(0) == 'InfoStat = 2'

我用

re.sub

所有文本

请告诉我,如何在不影响其他人的情况下更改特定行中 InfoStat 的值。

【问题讨论】:

    标签: python notepad++


    【解决方案1】:

    无需评论您通过特定程序来驱动这一点的努力,使用标准库 configparser 模块可以显着清理数据的读取。这是一个简化版:

    import configparser
    
    StatMod = 20
    
    config = configparser.ConfigParser()
    config.read('Database.ini')
    
    for section in config.sections():
        for k, v in config[section].items():
            if 'infostat' in k:  # configparses squashes case
                print(f"[{section}]")
                print(f"InfoStat={int(v) * StatMod}")
    

    【讨论】:

      【解决方案2】:

      您可以使用 splitting by '\n\n` 并替换每个部分,例如,

      import re
      
      FixedStat = 0
      StatMod = 20
      Result = 0
      FixedStatStr = ""
      
      
      _content_for_demo = """[1 StatsObject]
      InfoStat=1
      
      [2 StatsObject]
      InfoStat=2
      """
      
      content = editor.getText()
      pattern = r'InfoStat=(\d+)'
      for section in content.split('\n\n'):
          match = re.search(pattern, section)
          if match:
              value = int(match.group(1)) * StatMod
              val = 'InfoStat={}'.format(value)
              x = re.sub(match.group(), val, section)
              # print(x) debug
              editor.setText(content)
      

      【讨论】:

        【解决方案3】:

        如果您想使用正则表达式替换而不是另一个答案中建议的 ConfigParser 模块,最好通过将回调传递给 re.sub 而不是固定替换字符串来一次性完成整个操作:

        import re
        
        STAT_MOD = 20
        STAT_EXP = re.compile("(?P<prefix>InfoStat=)(?P<stat>[0-9]+)")
        
        def fixStat(m):
            fixed = int(m.group("stat")) * STAT_MOD
            return "{}{}".format(m.group("prefix"), fixed)
        
        def fixContent(c):
            return STAT_EXP.sub(fixStat, c)
        
        content = editor.getText()
        editor.setText(fixContent(content))
        

        【讨论】:

          【解决方案4】:

          感谢所有回复的人。

          我通过以下方式解决了我的问题:

          import configparser
          
          StatMod = 20
          
          config = configparser.ConfigParser()
          config.read('Database.ini')
          
          for section in config.sections():
              for k, v in config[section].items():
                  if 'infostat' in k:
                      OldValue = int(config.get(section, "infostat"))
                      if (OldValue == 0): continue
                      # print("OldValue =", OldValue)
                      NewValue = int(OldValue * StatMod)
                      # print("NewValue =", NewValue)
                      config.set(section, "infostat", str(NewValue))
                      # print(config.get(section, "infostat"))
          
          with open('Database.ini', "w") as config_file:
              config.write(config_file)
          

          【讨论】:

            猜你喜欢
            • 2011-03-02
            • 2019-12-16
            • 1970-01-01
            • 1970-01-01
            • 2011-05-07
            • 1970-01-01
            • 2017-02-09
            • 2021-12-14
            • 1970-01-01
            相关资源
            最近更新 更多