【问题标题】:How to select and add entry to a markdown file in Python?如何在 Python 中选择并添加条目到 Markdown 文件?
【发布时间】:2019-07-12 03:21:06
【问题描述】:

我有一个data.md 文件如下:

## intent:greet
- hey
- hello
- hi
- good morning
- good evening
- hey there

## intent:goodbye
- bye
- goodbye
- see you around
- see you later

## intent:affirm
- yes
- indeed
- of course
- that sounds good
- correct

## intent:deny
- no
- never
- I don't think so
- don't like that
- no way
- not really

现在我想在## intent:affirm 中添加一个新示例yes, I affirm,使其变为如下:

## intent:affirm
- yes
- indeed
- of course
- that sounds good
- correct
- yes, I affirm

如何在 Python 中实现这一点?

目前,我不知道从什么开始,因为我是 Python 新手,所以在在这里寻求帮助之前除了在线搜索相关文章之外,还没有做任何具体的事情。

【问题讨论】:

标签: python markdown


【解决方案1】:

这比看起来要困难一些,因为您不能只在 python 中编辑文件(除非它位于末尾)。所以可以先将文件读入数组,然后再重新写入。例如:

# Load the file into file_content
file_content = [ line for line in open('data.md') ]

# Overwrite it
writer = open('data.md','w')

for line in file_content:
    # We search for the correct section
    if line.startswith("##"):
        section = line.strip()

    # Re-write the file at each iteration
    writer.write(line)

    # Once we arrive at the correct position, write the new entry
    if section == "## intent:affirm" and line.strip() == "- correct":
        writer.write("- yes, I affirm\n")

writer.close()

【讨论】:

  • 它删除了字符串末尾的\n,以及字符串开头和结尾的空格
  • 我的错,应该是writer。我刚刚编辑了它
【解决方案2】:

您将不得不重写文件,如果您仍然可以访问,请使用复制/粘贴并在新文件中插入复制的文件和您要添加的部分。您无法更改它,因为它是 os 的东西,而不是 python。您可以使用操作系统中的终端或命令行替换文件。

窗户:

REPLACE [Drive:][path]SourceFiles [Drive:][path2] [/A] [/P] [/R] [/W] 其中:

/A 是任何丢失的文件

/P 提示确认

/R 甚至是替换只读文件

/W是等待/暂停(最初用于软盘)

Linux:

在 tmp 文件夹中创建并保存新文件,然后在终端中:

cat /tmp/new-file | sudo tee /home/user/(insert more folders and file if needed)

OS X/Mac:

我不确定如何执行此操作,因为我从来没有使用过 mac,但是 Google 或 StackExchange 中的某些社区。​​p>

【讨论】:

    猜你喜欢
    • 2022-01-27
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 2020-09-07
    相关资源
    最近更新 更多