簡體   English   中英

在 python 中連接具有條件的文本文件行

[英]Concatenate text file lines with condition in python

我有一個這種格式的文本文件:

0.jpg 12,13,14,15,16
0.jpg 13,14,15,16,17
1.jpg 1,2,3,4,5
1.jpg 2,3,4,5,6

我想檢查圖像名稱是否相同,然后將這些行連接成一行,格式如下:

0.jpg 12,13,14,15,16 13,14,15,16,17
1.jpg 1,2,3,4,5 2,3,4,5,6

我試過這樣的事情,但不知道如何進行實際比較,也不太清楚應用什么邏輯,因為將采用第一line_elements[0]並將其與其他行的line_elements[0]進行比較

with open("file.txt", "r") as input:       # Read all data lines.
    data = input.readlines()
with open("out_file.txt", "w") as output:  # Create output file.
    for line in data:                      # Iterate over data lines.
        line_elements = line.split()       # Split line by spaces.
        line_updated = [line_elements[0]]  # Initialize fixed line (without undesired patterns) with image's name.
        if line_elements[0] = (next line's line_elements[0])???:
            for i in line_elements[1:]:    # Iterate over groups of numbers in current line.
               tmp = i.split(',')          # Split current group by commas.
               if len(tmp) == 5:
                  line_updated.append(','.join(tmp))

            if len(line_updated) > 1:      # If the fixed line is valid, write it to output file.
               output.write(f"{' '.join(line_updated)}\n")

可能是這樣的:

for i in range (len(data)):
if line_elements[0] in line[i] == line_elements[0] in line[i+1]:

   line_updated = [line_elements[0]]
   for i in line_elements[1:]:    # Iterate over groups of numbers in current line.
      tmp = i.split(',')          # Split current group by commas.
      if len(tmp) == 5:
         line_updated.append(','.join(tmp))

   if len(line_updated) > 1:      # If the fixed line is valid, write it to output file.
      output.write(f"{' '.join(line_updated)}\n")

將行的第一個字段保存在變量中。 然后檢查當前行的第一個字段是否等於該值。 如果是,則將 append 寫入該值,否則寫入保存的行並開始新的 output 行。

current_name = None

with open("out_file.txt", "w") as output:
    for line in data:
        name, values = line.split()
        if name == current_name:
            current_values += ' ' + values
            continue
        if current_name:
            output.write(f'{current_name} {current_values}\n')
        current_name, current_values = name, values
    # write the last block
    if current_name:
        output.write(f'{current_name} {current_values}\n')

暫無
暫無

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

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