在降价文件中搜索 Python 字符串并在之后附加一个字符串

Search a Python string in markdown file and append a string afterwards

对于 NLP 任务,我有几个降价存储我的训练数据。

##intent:greet
- Hi
- Hello
- Good Day
- Good Morning
- Good Evening

##intent:say_thank_you
- Thank you
- Thx
- awesome
- great
- thank you very much

我在与机器人通信时生成了新的训练数据。加载、清理等后,我会得到一个 dict.

{0 : {
    'intent':'greet',
    'data':'good day sir'
    },
1 : {
    'intent':'greet',
    'data':'good afternoon'
    },
2 : {
    'intent':'say_thank_you',
    'data':'good job
    }
}

现在我想将这些句子附加到我的 md 文件中。我认为最简单的方法是直接在 ##intent:<intentname>

之后

我的第一个静态方法如下:

intent = 'greet'
identifier = "##intent:"+intent
with open('<myPath.md>') as myfile:
    if identifier in myfile.read():
        print("found intent")
    else:
        print("no intent with name greet")

虽然我有一个有效的 md-File 意图 greet 我找不到代码中的行。我假设我无法通过这种方式在文件中搜索降价语法。

有没有办法在不更改文件的情况下在 md 文件中搜索 markdown?我注意到一些将文件转换为 HTML 的建议,但有更简单的方法吗?

我的策略是创建一个新文件,将行复制到其中。当您找到要查找的部分时,请添加新行。完成后,删除源并使用新文件。

像这样的东西应该可以工作:

from pathlib import Path

def add_identifier(filename: str, key: str, item: str):
    source_file = Path(filename) # intent.txt
    dest_file = source_file.with_suffix('.replaced' + source_file.suffix) # intent.replaced.txt
    
    found = False
    with open(source_file) as f, open(dest_file, 'w') as rf:
        for line in f:
            # copy line 
            rf.write(line)
            if f'##intent:{key}' in line:
                found = True
                # insert new identifier
                rf.write(f'- {item}\n')
        if not found:
            # create a new section and add the identifier
            rf.write(f'\n\n##intent:{key}\n')
            rf.write(f'- {item}\n')
        
    # remove original and rename new file
    # source_file.unlink()
    # dest_file.rename(source_file)
    
# usage
add_identifier('intent.txt', key='greet', item="hello m'lady")

我添加了一个检查以添加一个新部分,如果它不存在于原始文件中。