简体   繁体   English

如何在文件中搜索单词并将整行替换为新行?

[英]How to search a word in a file and replace the entire line with a new line?

I have a file (with extension.hgx) that has some data like this: 我有一个文件(带有extension.hgx),其中包含一些数据,如下所示:

length             =  0.00000783
height             =  48
RATIO              =  2
X                  =  1.0
Y                  =  1.0

I would like to open the file and replace the two lines: 我想打开文件并替换两行:


height             =  48
RATIO              =  2

With: 带有:


height             =  8
RATIO              =  8

I tried parsing the file and could search for the "height" and "RATIO". 我尝试解析该文件,并可以搜索“高度”和“比率”。 Unfortunately, I could not replace the line with new line and re-save the file. 不幸的是,我无法用新行替换该行并重新保存文件。 In my case the problem is that, that in the file the value of parameters eg height(=48) varies and sometimes has uneven spaces in between. 在我的情况下,问题是文件中参数的值(例如height(= 48))变化,并且有时它们之间的间隔不均匀。 I want to replace this complete line with-- height = 8 我想用-height = 8代替这条完整的线

I have written the following code 我写了下面的代码

import fileinput
import sys
f = open('test.hgx','r')
line_num = 0
search_phrase = "height"
for line in f.readlines():
    line_num += 1
    if line.find(search_phrase) >= 0:
        print line_num

newline='height                  =  8'
lnum=1
for line in fileinput.FileInput("test.hgx",inplace=1):
    if lnum==line_num:
        result = newline+"\n"
    else:
        result=line
    lnum=lnum+1    
    sys.stdout.write(result)
    print line

This does not help replace complete line and save the file again. 这无助于替换完整行并再次保存文件。 returns empty file.Any help would be greatly appreciated. 返回空文件。任何帮助将不胜感激。

Regards, Ris 问候,里斯

How's this? 这个怎么样?

with open('test.hgx') as f:  lines = f.read().splitlines()
with open('test.hgx', 'w') as f:
  for line in lines:
    if line.startswith('height') or line.startswith('RATIO'):  
      f.write(line.rsplit(' ', 1)[0] + ' 8\n')
    else:
      f.write(line + '\n')

you need to stop iterating in the first loop after finding the "height" line: 您需要在找到“高度”行后在第一个循环中停止迭代:

if line.find(search_phrase) >= 0:
    print line_num
    break

I propose to use regex tool: 我建议使用正则表达式工具:

import re

regx = re.compile('^(([^ \t]+)[ \t]+=.+)',re.MULTILINE)

new = '''\
RATIO              =  8
sdjlkhbfvjhdbfjhsdoijhfsdhfksdhfh
height             =  8
'''

dic = dict(mat.group(2,1) for mat in regx.finditer(new))

regchange = re.compile('^('+'|'.join(dic.iterkeys())+')[ \t]+=[^\r\n]+',re.MULTILINE)

with open(filename,'r+') as f:
    content = f.read()
    f.seek(0,0)
    f.write(regchange.sub(lambda m: dic[m.group(1)],content))
    f.truncate()

You put in new the lines you want to take place in the file, no matter in which order (that's why I wrote 'RATIO' line before 'height' line in my exemple, to show) 无论您以什么顺序将行添加到文件中(这就是为什么我在示例中的“ height”行之前写了“ RATIO”行)

The program manages to obtain the dictionary dic that is used to create the regex that allows to search for the lines to be replaced and to substitute them with lines recorded in dic as values corresponding to the first name of the line 该程序设法获得字典dic ,该字典dic用于创建正则表达式,该正则表达式允许搜索要替换的行并将其替换为dic中记录的行,作为与该行的名字相对应的值

The line 'sdjlkhbfvjhdbfjhsdoijhfsdhfksdhfh' has no importance. “ sdjlkhbfvjhdbfjhsdoijhfsdhfksdhfh”行不重要。 I put it in new to show that the regex regx matches only with lines of the format 'name = something' 我将其放在新的位置以表明regex regx仅与“名称=某物”格式的行匹配

This code should work as-is. 此代码应按原样工作。 You have just to give a file's name to filename ; 您只需要给filename指定一个文件名即可; If any error, give it please. 如果有任何错误,请提供。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在文本文件中搜索单词并用 Python 打印整行? - How to search for word in text file and print the entire line with Python? 根据使用Python的搜索替换文本文件中的整行 - Replace entire line in a text file based on search using Python 如何在文本文件中搜索行的内容,替换行并另存为新文件? - How do I search for contents of a line in a text file, replace the line, and save as a new file? 如何在文本文件中搜索术语,然后用python中的新行替换整行? - How to search for a term in a text file then replace that whole line with a new line in python? 如何在正确的文件行中搜索单词 - how to search word in a line of file correct python在文件中搜索字符串,将整行+下一行返回新文本文件 - python search for string in file return entire line + next line into new text file 在一行中搜索一个字符串,然后用另一个字符串替换整行 - Search for a string in a line and replace the entire line with another string python用空行替换单词或在单词后添加新行 - python replace a word with empty line or append a new line after the word 在行中搜索 substring 然后在文本文件中替换该行 - Search substring in line and then replace that line in text file 在 Python 中搜索并替换文件中的一行 - Search and replace a line in a file in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM