重新排列txt内容脚本



我有一份捕食者及其相应猎物的列表,格式如下:

狼:绵羊、鸡、兔子
狮子:斑马、长颈鹿、瞪羚

并希望将其转换为以下格式:

Wolf Sheep
Wolf Chicken
狼兔
狮子斑马
狮长颈鹿
狮瞪羚

到目前为止,我已经尝试过这个代码来区分捕食者和猎物

with open('test.txt','r') as in_file:
stripped = (line.strip() for line in in_file)
split = (line.split(":") for line in stripped if line)
pred = []
for line in split:
pred.append(line[0])
with open('test.txt','r') as in_file:
stripped = (line.strip() for line in in_file)
split = (line.split(":") for line in stripped if line)
preys = []
for line in split:
preys.append(line[1])
prey = (line.split(",") for line in preys if line)

但将它们结合起来才是问题所在。我尝试过类似的东西:

with open('test.txt','r') as in_file:
stripped = (line.strip() for line in in_file)
i=0
while i < line_count:
rows.append(pred[i])
for line in prey:
rows.append(line[0])
i+=1

您可以一次处理一行,并按如下方式编写输出:

with open('test.txt') as f_input, open('output.txt', 'w') as f_output:
for line in f_input:
predator, prey = line.split(':')

for p in prey.split(','):
f_output.write(f'{predator} {p.strip()}n')

给你:

Wolf Sheep
Wolf Chicken
Wolf Rabbit
Lion Zebra
Lion Giraffe
Lion Gazelle

您可以读取以下项目:

with open('test.txt','r') as in_file:
dict_predators = {}
for line in in_file:
dict_predators[line.split(':')[0]] = line.split(':')[1].replace('n', '').split(',')

首先用":"分隔行,使用这两个元素——第一部分作为字典中的键,第二部分作为字典值的列表(我使用了replace来去掉换行符(,然后用","将它们分割成字符串(之前有一个空格,因为当你打印出来时已经要使用空格了(

你可以把它们写进这样的文件:

with open('test2.txt','w') as in_file:
for k,v in dict_predators.items():  # go through all the elements in the dictionary
for item in v:  # go through all the elements of the list of values at that key
in_file.write(f"{k}{item}n")

如果您可以使用itertoolsre模块,我会使用以下内容:

import itertools, re
with open('test.txt', 'r') as inFile, open('test2.txt', 'w') as outFile:
for line in inFile:
splitted = re.split(":|,", line.strip())
predator = splitted[0].strip()
preys = [ prey.strip() for prey in splitted[1:] ]
content = zip(itertools.repeat(predator), preys)
outFile.write('n'.join([ ' '.join(item) for item in content ]))

工作原理:

  1. 逐行读取输入文件
  2. 对于每一行,它首先strip该行,然后split它使用coloncomma作为分隔符
  3. 将捕食者和猎物放在两个命名变量中,以使代码清晰明了
  4. 使用CCD_ 7和CCD_
  5. 创建一个";加入";内容中的项对项,使用空格作为连接符
  6. 创建一个字符串,以'\n'作为连接符连接以前的列表元素
  7. 将其写入outFile

相关内容