如何根据文本文件的关联值从文本文件中提取公共行?

2024-09-29 01:34:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有3个文本文件:

列表1.txt:

032_M5, 5
035_M9, 5
036_M4, 3
038_M2, 6
041_M1, 6

列表2.txt:

032_M5, 6
035_M9, 6
036_M4, 5
038_M2, 5
041_M1, 6

List3.txt文件:

032_M5, 6
035_M9, 6
036_M4, 4
038_M2, 5
041_M1, 6

其中所有3个文本文件中的行的第一部分(即字符串)相同,但第二部分(即编号)更改。你知道吗

我想从中得到三个输出文件:

Output1.txt-->;数字对应字符串的所有行都不同。 示例:

036_M4 3, 5, 4

Output2.txt-->;数字对应字符串的所有行都相同。 示例:

041_M1, 6

Output3.txt-->;至少两个数字对应于一个字符串的所有行都相同(这也包括Output2.txt的结果)。 示例:

032_M5, 6
035_M9, 6
038_M2, 5
041_M1, 6

然后我需要Output3.txt中包含数字1、数字2、数字3、数字4、数字5和数字6的行数。你知道吗

这是我试过的。它给了我错误的输出。你知道吗

from collections import defaultdict
data = defaultdict(list)
for fileName in ["List1.txt","List2.txt", "List3.txt"]:
    with open(fileName,'r') as file1:
        for line in file1:
            col1,value = line.split(",") 
            data[col1].append(int(value))

with open("Output3.txt","w") as output:
    for (col1),values in data.items():
        if len(values) < 3: continue             
        result = max(x for x in values)                     
        output.write(f"{col1}, {result}\n")

Tags: 字符串ingttxt示例fordata数字
2条回答

这是一种不使用任何python模块的方法,它完全依赖于本机内置的python函数:

with open("List1.txt", "r") as list1, open("List2.txt", "r") as list2, open("List3.txt", "r") as list3:
  # Forming association between keywords and numbers.
  data1 = list1.readlines()
  totalKeys = [elem.split(',')[0] for elem in data1]
  numbers1 = [elem.split(',')[1].strip() for elem in data1]
  numbers2 = [elem.split(',')[1].strip() for elem in list2.readlines()]
  numbers3 = [elem.split(',')[1].strip() for elem in list3.readlines()]
  totalValues = list(zip(numbers1,numbers2,numbers3))
  totalDict = dict(zip(totalKeys,totalValues))

  #Outputs
  output1 = []
  output2 = []
  output3 = []
  for key in totalDict.keys():
    #Output1
    if len(set(totalDict[key])) == 3:
      output1.append([key, totalDict[key]])
    #Output2
    if len(set(totalDict[key])) == 1:
      output2.append([key, totalDict[key][0]])
    #Output3
    if len(set(totalDict[key])) <= 2:
      output3.append([key, max(totalDict[key], key=lambda elem: totalDict[key].count(elem))])

  #Output1
  print('Output1:')
  for elem in output1:
    print(elem[0] + ' ' + ", ".join(elem[1]))
  print()

  #Output2
  print('Output2:')
  for elem in output2:
    print(elem[0] + ' ' + " ".join(elem[1]))
  print()

  #Output3
  print('Output3:')
  for elem in output3:
    print(elem[0] + ' ' + " ".join(elem[1]))

上述结果将是:

Output1:
036_M4 3, 5, 4

Output2:
041_M1 6

Output3:
032_M5 6
035_M9 6
038_M2 5
041_M1 6

max给出列表中最大的数字,而不是最常出现的数字。为此,请使用statistics.mode

from collections import defaultdict
from statistics import mode

data = defaultdict(list)
for fileName in ["List1.txt","List2.txt", "List3.txt"]:
    with open(fileName,'r') as file1:
        for line in file1:
            col1,value = line.split(",") 
            data[col1].append(int(value))

with open("Output1.txt","w") as output:
    for (col1),values in data.items():
        if len(values) < 3: continue
        if values[0] != values[1] != values[2] and values[0] != values[2]:
            output.write(f"{col1}, {values[0]}, {values[1]}, {values[2]}\n")

with open("Output2.txt","w") as output:
    for (col1),values in data.items():
        if len(values) < 3: continue
        if values[0] == values[1] == values[2]:
            output.write(f"{col1}, {values[0]}\n")

with open("Output3.txt","w") as output:
    for (col1),values in data.items():
        if len(values) < 3: continue
        if len(set(values)) >= 2:
            output.write(f"{col1}, {mode(values)}\n")

相关问题 更多 >