【问题标题】:Adding a Custom ID with Python & Regex使用 Python 和正则表达式添加自定义 ID
【发布时间】:2021-05-08 12:30:52
【问题描述】:

我在 Markdown 中有一个文档,我想为每个城市条目添加一个自定义 ID。文档的基本布局如下:

#Country

## StateA

### CityA
#### Population
#### Government
#### History

### CityB
#### Population
#### Government
#### History

## StateB

### CityA
#### Population
#### Government
#### History

### CityB
#### Population
#### Government
#### History

我想为每个城市添加一个带有计数器的自定义 ID。例如,ID 看起来像:

#USA

## FL

### US_FL_00001
### US_FL_00002
### US_FL_00003

## GA

### US_GA_00001
### US_GA_00002
### US_GA_00003

我知道使用正则表达式来选择城市相对简单,使用 re.findall() 和 re.sub() 作为 '###' 标头,但我怎样才能拉入状态和 ID 的连续计数器?

【问题讨论】:

    标签: python regex text markdown


    【解决方案1】:

    看起来您的示例输入和示例输出可能存在差异,但我的答案基于您的示例输出,您可以对其进行调整以满足您的需求。

    这个想法是读入输入文件并逐行测试以查看该行是否代表一个国家、一个州或一个城市。然后将这些存储到以 '####' 开头的行,然后将结果与计数器一起输出到新文件。

    import re
    
    with open('input.md', 'r') as f:
        # read in the original file
        text = f.readlines()
    
    # open the output file and loop through the original data
    with open('output.md', 'w') as o:
        country_counter = counter = 0
        for line in text:
            # get the country
            m = re.match(r'^#([A-Za-z]+)', line)
            if m:
                country = m.group(1)
                # this checks to see if it is the first country
                # in the file. If so then we don't want the leading
                # newline characters
                if country_counter == 0:
                    o.write(f'#{country}')
                else:
                    o.write(f'\n\n#{country}')
                country_counter += 1
    
            # get the state
            m = re.match(r'^##\s([A-Za-z]+)', line)
            if m:
                state = m.group(1)
                # reset the counter
                counter = 0
                o.write(f'\n\n## {state}\n')
    
            # get the city
            m = re.match(r'^###\s([A-Za-z]+)', line)
            if m:
                # increase the counter and output the results
                # the counter is padded to 5 digits.
                counter += 1
                o.write(f'\n### {city}_{state}_{counter:05}')
    

    【讨论】:

    • 当我尝试运行代码时,它说在第 38 行 NameError: name 'counter' is not defined。还有 NameError: name 'city' is not defined
    • @mhshaaban 我通过将第 9 行更改为 country_counter = counter = 0 来编辑脚本。这应该可以解决问题。
    • 顺便说一下,提供的脚本不会进行任何错误检查,并且可能会因输入错误而失败 例如,如果在任何州之前列出了一个城市,您将收到 state 的错误没有定义的。但是,只要输入格式正确,我希望脚本能够按原样工作。
    • 是的,正如我在答案中所说,脚本基于给出的示例。偏离这一点需要对脚本进行调整(如您所见)。 @Waylan 感谢您的编辑。
    • 感谢修复了计数器问题!谢谢!如果我想保留 #### Population #### Government #### History 之类的其他文本,我应该遵循相同的模式吗?还是会有更优雅的解决方案?
    猜你喜欢
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 2019-12-05
    • 2013-03-24
    相关资源
    最近更新 更多