我有一份捕食者及其相应猎物的清单,其格式如下:
狼:羊、鸡、兔
狮子:斑马,长颈鹿,羚羊
并希望将其转换为以下格式:
狼羊
狼鸡
狼兔
狮子斑马
狮子长颈鹿
狮子瞪羚
到目前为止,我已经尝试了这个代码来区分捕食者和猎物。
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发布于 2022-02-06 18:33:29
您可以一次处理一行输出,如下所示:
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发布于 2022-02-06 00:00:06
您可以在下面的项目中阅读:
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(',')首先用“:”分隔行--第一部分作为字典中的键,第二部分作为字典中值的列表(我用替换来消除换行符),然后用‘拆分',使它们成为字符串(之前有空格,因为当您将它们打印出来时已经要使用空格)。
你可以把它们写到这样的文件中:
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")发布于 2022-02-06 00:23:39
如果您可以使用itertools和re模块,我将使用以下内容:
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 ]))它的工作原理:
separators;
colon和comma作为捕食者,然后使用colon和comma作为捕食者,并在两个命名变量中使用猎物使使用zip和itertools.repeat;
https://stackoverflow.com/questions/71003084
复制相似问题