python - 替换给定文本文件中指定位置的特定单词 (Python)

标签 python python-3.x

我有一个元组列表,每个元组都包含一个要替换的单词及其来自给定文本文件的行号和列号位置。我想浏览文本文件并用字符替换该特定位置的特定单词(例如 [('word1', 1, 1), ('word2', 1, 9), ...]).

换句话说,给定一个特定的单词,它在文本文件中的行号和列号,我试图查找该单词并将其替换为字符,例如:

假设文本文件包含以下内容(假设其位置与显示的位置相同 - 未写在此处)

Excited him now natural saw passage offices you minuter. At by stack being court hopes. Farther so friends am to detract. Forbade concern do private be. Offending residence but men engrossed shy. Pretend am stack earnest arrived company so on. Felicity informed yet had to is admitted strictly how stack you.

假设要替换的单词是 stack ,在文本中的位置为第 3 行和 16 列,将其替换为字符*,

因此,在替换发生后,文本文件现在将具有以下内容:

Excited him now natural saw passage offices you minuter. At by stack being court hopes. Farther so friends am to detract. Forbade concern do private be. Offending residence but men engrossed shy. Pretend am * earnest arrived company so on. Felicity informed yet had to is admitted strictly how stack you.

我考虑过linecache但对于大型文本文件来说似乎效率很低。另外,考虑到我已经有了行号和列号,我希望有一种方法可以直接转到该位置并执行替换。

有人知道如何用 Python 实现这一点吗?

编辑

按照后续的讨论 issue,使用 numpy 的 genfromtxt 提出的初始解决方案(很可能)不适合因为需要文本文件的每一行都存在并且不被跳过(例如空行、以“w”开头的字符串以及“/*../”内的字符串)。

最佳答案

尝试这样的食谱:

import numpy as np
import os

def changethis(pos):
    # Notice file is in global scope
    appex = file[pos[1]-1][:pos[2]] + '*' + file[pos[1]-1][pos[2]+len(pos[0]):]
    file[pos[1]-1] = appex

pos = ('stack', 3, 16)
file = np.array([i for i in open('in.txt','r')]) #BEFORE EDIT: np.genfromtxt('in.txt',dtype='str',delimiter=os.linesep)
changethis(pos)
print(file)

结果是这样的:

[ 'Excited him now natural saw passage offices you minuter. At by stack being court hopes. Farther'
 'so friends am to detract. Forbade concern do private be. Offending residence but men engrossed'
 'shy. Pretend am * earnest arrived company so on. Felicity informed yet had to is admitted'
 'strictly how stack you.']

请注意,这是将一堆长字符串放入 numpy 中的一个技巧。数组,并以某种方式更改它们,但在插入位置元组的较长循环时应该是高效的。

编辑:由于@user2357112让我意识到文件阅读器的选择不是最合适的(尽管它适用于相关练习),所以我编辑了这个答案以提供相同的内容the follow up question中给出的解决方案.

关于python - 替换给定文本文件中指定位置的特定单词 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36895533/

相关文章:

yaml.load 和 yaml.safe_load 的 Python 区别

python-3.x - OpenCV图像形状元组解压缩

PostgreSQL 字段中的 Django ProgrammingError

python - 转义单引号 (') in raw string r' ...'

python - 如何按索引从列表中删除元素

python - 有没有一种优雅的方法可以将打印的语句追溯到打印它的代码行?

python - 如何从不同模型获取查询集的 json 响应列表?

python - 排序、打开和写入文件

python - 绘制直方图,使条形高度总和为 1(概率)

python - 连接文件中多行的字符串,以换行符分隔