【问题标题】:Removing a line from text从文本中删除一行
【发布时间】:2014-04-21 12:25:37
【问题描述】:

假设我有一个文本文档。我有一行。我想删除该行上的文本并用另一个文本替换它。我该怎么做呢?文档上没有这方面的内容,在此先感谢!

【问题讨论】:

  • 您是否尝试过打开两个文件(源文件和目标文件),然后使用 readline 函数遍历源文件的每一行,进行搜索/替换,然后将其写入目标文件writeline?
  • 正如它目前所写的,这个问题有点误导。这实际上是this question 的后续行动(见 cmets)。

标签: python replace pyqt pyqt4 qscintilla


【解决方案1】:

未经测试:使用 .readlines() 读取文件的行,然后替换该列表中的行号索引。最后,它连接行并将其写入文件。

with open("file", "rw") as fp:
    lines = fp.readlines()
    lines[line_number] = "replacement line"
    fp.seek(0)
    fp.write("\n".join(lines))

【讨论】:

  • 尽管未经测试,但逻辑本身应该可以工作,即使实际代码可能不会,所以 +1。
  • 如果替换使内容变短,会不会因为没有被覆盖而将部分原文件留在最后?
  • @three_pineapples 我认为你是对的。您可能想删除原始内容而不是寻找,但基本思想仍然如此 +1。
  • 虽然这个答案没有任何问题,但它实际上与问题无关(这是关于 qscintilla 编辑器控件)。
【解决方案2】:

要在 QScintilla 中替换一行,您需要先选择该行,如下所示:

    # as an example, get the current line
    line, pos = editor.getCursorPosition()
    # then select it
    editor.setSelection(line, 0, line, editor.lineLength(line))

选中该行后,您可以将其替换为:

    editor.replaceSelectedText(text)

如果你想用另一行替换一行(在这个过程中会被删除):

    # get the text of the other line
    text = editor.text(line)
    # select it, so it can be removed
    editor.setSelection(line, 0, line, editor.lineLength(line))
    # remove it
    editor.removeSelectedText()
    # now select the target line and replace its text
    editor.setSelection(target, 0, target, editor.lineLength(target))
    editor.replaceSelectedText(text)        

【讨论】:

    猜你喜欢
    • 2013-05-13
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 2015-12-22
    • 2011-01-05
    相关资源
    最近更新 更多