【发布时间】:2021-04-27 08:31:30
【问题描述】:
我对 python 完全陌生,我有以下问题。我已经搜索了很多,虽然我可以找到类似的问题和答案,但我找不到一个可以解决我的可变性质的问题。所以这里是:
我有一个文件,在几个地方(数百个)有一行显示
【问题讨论】:
-
你试过什么代码?你能更具体地说明这些例子吗?提供您使用的每个文件类别的示例以及您希望输出的外观。
标签: python variables text replace
我对 python 完全陌生,我有以下问题。我已经搜索了很多,虽然我可以找到类似的问题和答案,但我找不到一个可以解决我的可变性质的问题。所以这里是:
我有一个文件,在几个地方(数百个)有一行显示
【问题讨论】:
标签: python variables text replace
正如@amquack 评论和 SO 指南要求的那样,您应该在此处发布您尝试过的代码示例,或者至少包含有关所需文件的完整信息。即使您得到了很好的答案并在此处接受,您也应该使用更完整的信息来编辑问题。
当我读到你的问题时,你有一个文件,比如 f1,看起来像
a
bunch
<text = " ">
of
<text = " ">
other
lines
<text = " ">
另一个文件f2 看起来像这样
string1
string2
string3
并且您想用来自f2 的行替换f1 中读取<text = " "> 的行。这是假设f2 包含的行数与<text = " "> 中的<text = " "> 行数相同的可能性@
# get the contents of your files using the with statement so
# the interpreter cleans up after you
with open('f1', 'r') as infile:
f1_lines = infile.readlines()
with open('f2', 'r') as infile:
f2_lines = infile.readlines()
# create a new file for output
with open('out', 'w') as outfile:
# loop over the lines in the text you want to modify
for line in f1_lines:
if line.strip() == '<text = " ">':
# this is a line you want to replace, so pop the next
# line you want to insert off of f2_lines and write
# it to the output file
outfile.write(f2_lines.pop(0))
if len(f2_lines) == 0:
# if that was the last line to insert, add a newline
# character in case there are more lines to copy over
# from f1
outfile.write('\n')
else:
# the text you want to replace is not in this line, so
# copy this line to the output file
outfile.write(line)
请注意,如果您有非常大的文件或在大量文件上运行此代码,则 for 循环和 f2_lines.pop 的执行效果将不如其他方法。上面的文件内容和代码生成了一个类似这样的文件
a
bunch
string1
of
string2
other
lines
string3
【讨论】:
您没有指定结果是否必须在另一个文件中,但我假设是这样。
假设foo.txt 是包含要匹配的模式的文件(即<text = " ">),而replacements.txt 包含要逐行放置的替换,这就是执行此任务的方法。
import re
with open('foo.txt') as f:
lines = [line.strip() for line in f.readlines()]
with open('replacements.txt') as f:
replacements = [line.strip() for line in f.readlines()]
首先我们读取文件的内容(从空格和结束符中去除每一行)。
j = 0
for i, line in enumerate(lines):
result = re.match('<text = " ">', line)
if result and j < len(replacements):
lines[i] = replacements[j]
j += 1
然后我们为替换数组设置一个计数器,并为每一行搜索要替换的字符串。
如果找到并且我们有替换项,我们将继续使用第 j 个元素更改该行。
lines = [line + '\n' for line in lines]
with open('foo_modified.txt', 'w') as f:
f.writelines(lines)
然后我们将修改后的行连接在一起(手动添加结束行字符,之前已剥离),并将其写入另一个文件。
【讨论】: