簡體   English   中英

從另一個文本文件替換文本文件中的行

[英]replace lines in a text file from another text file

我是python的新手,正在嘗試一個新問題,但無法解決。 我有一個名為replace.txt的文本文件,其內容如下:

 81, 40.001, 49.9996, 49.9958
 82, 41.1034, 54.5636, 49.9958
 83, 44.2582, 58.1856, 49.9959
 84, 48.7511, 59.9199, 49.9957
 85, 53.4674, 59.3776, 49.9958
 86, 57.4443, 56.6743, 49.9959
 87, 59.7, 52.4234, 49.9958

現在,我還有一個名為實際數據的文件,它具有大量的數據,例如上面的數據。現在,我想通過匹配第一個數字(例如在actualdata.txt中搜索“ 81”)來替換actualdata.txt中的上述行並替換它與replace.txt中具有“ 81”的行

這里的actualdata.txt看起來像這樣:

--------lines above--------
81,  40.0           ,  50.0           ,  50.0           
82,  41.102548189607,  54.564575695695,  50.0           
83,  44.257790830341,  58.187003960661,  50.0           
84,  48.751279796738,  59.921728571875,  50.0           
85,  53.468166336575,  59.379329520912,  50.0           
86,  57.445611860313,  56.675542227082,  50.0           
87,  59.701750075154,  52.424055585018,  50.0           
88,  59.725876387298,  47.674633684987,  50.0           
89,  57.511209176153,  43.398353484768,  50.0           
90,  53.558991157616,  40.654756186166,  50.0           
91,  48.853051436724,  40.06599229952 ,  50.0           
92,  44.335578609695,  41.75898487363 ,  50.0           
93,  41.139049269956,  45.364964707822,  50.0           
94,  4.9858306110506,  4.9976785333108,  50.0           
95,  9.9716298556132,  4.9995886389273,  50.0           
96,  4.9712790759448,  9.9984071508336,  50.0           
97,  9.9421696473295,  10.002460334272,  50.0           
98,  14.957223264745,  5.0022762348283,  50.0           
99,  4.9568005100444,  15.000751982196,  50.0
------lines below---------- 

我該怎么做,請幫助我嘗試使用fileinput並替換,但沒有得到輸出。

這是我仍在即興使用的示例代碼(這對於一行來說是有效的):

oldline='        82,  41.102548189607,  54.564575695695,  50.0'
newline='    81, 40.001, 49.9996, 49.9958'

for line in fileinput.input(inpfile, inplace = 1): 
      print line.replace(oldline,newline),

這是我最后寫的代碼:

replacefile= open('temp.txt','r')
for line1 in replacefile:
    newline = line1.rstrip()
        rl=newline
        rl=rl.split()
        search =rl[0]
        with open(inpfile) as input:
        intable = False
        for line in input:
            fill=[]
            if line.strip() == "*NODE":
            intable = True
            if line.strip() == "---------------------------------------------------------------":
            intable = False
            if intable:
              templine=(line.rstrip())
              tl=line.rstrip()
              tl= tl.split()
              if tl[0] == search:
                oldline=templine
                for line2 in fileinput.input(inpfile, inplace = 1): 
                    line2.replace(oldline,newline)

但我無法獲取輸出,刪除了actualdata.txt的內容,請幫我提供此輸出,我想要的是像這樣更改actualdata.txt:

  -------lines above------
     81, 40.001, 49.9996, 49.9958
     82, 41.1034, 54.5636, 49.9958
     83, 44.2582, 58.1856, 49.9959
     84, 48.7511, 59.9199, 49.9957
     85,  53.468166336575,  59.379329520912,  50.0           
    86,  57.445611860313,  56.675542227082,  50.0           
    87,  59.701750075154,  52.424055585018,  50.0           
    88,  59.725876387298,  47.674633684987,  50.0           
    89,  57.511209176153,  43.398353484768,  50.0           
    90,  53.558991157616,  40.654756186166,  50.0 
    -------lines below------ 

使用的FileInput模塊來代替就位行:

import fileinput
def get_next_line(fptr):
    x = fptr.readline()
    if(x != ''):
        return x.strip(), x.strip().split()[0].strip()
    else:
        return '',''

f = open("replace.txt", "r")

f_line, f_line_no = get_next_line(f)

for line in fileinput.input("actualdata.txt", inplace=True):
    if(line.strip().split()[0].strip() == f_line_no):          #if line number matches
        print(f_line)                                          # write newline
        f_line, f_line_no = get_next_line(f)                   # Get next newline
    else:                                                      # Otherwise
        print(line.strip())                                    # write original one

順便說一下,我正在使用python3 如果您使用的是python2,請進行適當的更改

replace.txt也大嗎? 如果沒有,您可以先將其加載到內存中,構建一個字典,然后用它替換actualdata.txt行。

這是我在做什么:

  1. 首先打開replace.txt並構建字典。 由於您要用行的第一個值替換行,因此我們將其作為字典鍵。 並且其值將是您要替換的行。 喜歡:

     replacement_data = { '81': '81, 40.001, 49.9996, 49.9958', '82': 82, 41.1034, 54.5636, 49.9958, ... ... } 
  2. 接下來,我們開始actualdata.txt讀取actualdata.txt文件。 因此,我們必須查找是否要替換此行的第一個數字。 因此,我們將首先用,分割它,獲取第一個字符,然后查看它是否存在於replacement_data字典中。 如果存在,我們將替換它,否則,我們將忽略。

     line = "83, 44.257790830341, 58.187003960661, 50.0" first_char = line.split(',')[0].strip() #first char is 83 # lets check whether to replace it or not if first_char in replacement_data.keys(): # if key exists, we have to replace line = replacement_data[first_char] print line # so that it writes to file 

將所有部分放在一起:

import fileinput
import sys

inpfile = 'actualdata.txt'
replacement_file = 'replace.txt'

replacement_data = {}

with open(replacement_file) as f:
    for line in f:
        key = line.split(',')[0].strip()
        replacement_data[key] = line

for line in fileinput.input(inpfile, inplace = 1): 
    first_char = line.split(',')[0].strip()
    try:
        int(first_char)
        line = replacement_data[first_char]
        print line,
    except (ValueError, KeyError):
        print line,
        continue

它將原始文件生成為:

--------lines above--------
81, 40.001, 49.9996, 49.9958
82, 41.1034, 54.5636, 49.9958
...
...
86, 57.4443, 56.6743, 49.9959
87, 59.7, 52.4234, 49.9958 88,  59.725876387298,  47.674633684987,  50.0           
89,  57.511209176153,  43.398353484768,  50.0           
...        
99,  4.9568005100444,  15.000751982196,  50.0
------lines below---------- 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM